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.
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
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With