Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an element by the value of its attribute using JDOM?

Tags:

java

dom

xml

jdom

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?

like image 316
moorara Avatar asked Oct 14 '12 21:10

moorara


1 Answers

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

like image 174
rolfl Avatar answered Oct 11 '22 23:10

rolfl