Reputation: 4226
I have a xml file like the following one:
<?xml version="1.0" encoding="UTF-8" ?>
<config>
<admins>
<url name="Writer Admin">http://www.mywebsite.com/admins?cat=writer</url>
<url name="Editor Admin">http://www.mywebsite.com/admins?cat=editor</url>
</admins>
<users>
<url name="Critic User">http://www.mywebsite.com/users?cat=critic</url>
<url name="Reviewer User">http://www.mywebsite.com/users?cat=reviewer</url>
<url name="Reader User">http://www.mywebsite.com/users?cat=reader</url>
</users>
</config>
How can I select the "url" elements by the value of their "name" attributes using JDOM library in java? Is there any straightforward way or I have to select all the child elements and check for the desired element using a "for" loop? Is there any approach like the Linq in .Net?
Upvotes: 5
Views: 6026
Reputation: 17707
XPath is your friend... if you are using JDOM 2.x it is easier than JDOM 1.x, so, int JDOM 2.x it will be something like:
String query = "//*[@name= 'Critic User']";
XPathExpression<Element> xpe = XPathFactory.instance().compile(query, Filters.element());
for (Element urle : xpe.evaluate(mydoc))
{
System.out.printf("This Element has name '%s' and text '%s'\n",
urle.getName(), urle.getValue());
}
XPath is a 'different beast', but it makes some things (like this), a whole bunch easier to write.
The above 'query' basically says: Find all elements in the document which have an attribute called 'name', and the value of the name attribute is 'Critic User'.
Adjust to taste, and read the XPath tutorial: http://www.w3schools.com/xpath/default.asp
Edit: Of course, a better query would be: //url[@name= 'Critic User']
Upvotes: 5
Reputation: 55
Thank a lot for that.
I just noticed that rolfl inversed the arguments order in compile method. XPathFactory.instance().compile(query, Filters.element());
instead of XPathFactory.instance().compile(Filters.element(), query);
Good job however...
Upvotes: 0