Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search elements by attribute value

Tags:

jsoup

So I'm not sure if this is possible. But I want to scan over an XML document to find all elements which has a particular attribute value.

It doesn't matter what the element is or the attribute type is... I just need to find them based on attribute value.

e.g. I am looking for the word "duck"

<person name="Fred" thing="duck"/>
<person name="Mary"/>
<animal name="duck" thing="swims"/>

The first and third one should match, the second does not match.

Any ideas?

Many thanks.

like image 962
user1389920 Avatar asked Dec 05 '22 14:12

user1389920


2 Answers

I know this answer is well after the fact but I thought it would be useful to others. There is a better way than the method above:

Elements ducks = doc.select("person[*=duck]");

This will return elements only containing attributes with the value "duck".

Useful cheat sheat on jsoups website: http://jsoup.org/apidocs/org/jsoup/select/Selector.html

like image 112
Paddy Mallam Avatar answered Jan 19 '23 12:01

Paddy Mallam


Not shure if this is possible with a selector. But maybe you can try something like this:

final String input = "<person name=\"Fred\" thing=\"duck\"/>"
        + "<person name=\"Mary\"/>"
        + "<animal name=\"duck\" thing=\"swims\"/>";


Document doc = Jsoup.parse(input);
Elements withAttr = new Elements();


for( Element element : doc.getAllElements() )
{
    for( Attribute attribute : element.attributes() )
    {
        if( attribute.getValue().equalsIgnoreCase("duck") )
        {
            withAttr.add(element);
        }
    }
}
like image 23
ollo Avatar answered Jan 19 '23 11:01

ollo