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?
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']
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