5

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?

moorara
  • 3,897
  • 10
  • 47
  • 60

2 Answers2

5

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

Israel Perales
  • 2,192
  • 2
  • 25
  • 30
rolfl
  • 17,539
  • 7
  • 42
  • 76
  • 1
    If performance isn't an issue, XPath is probably the way to go. You can grab specific elements very selectively. But even if looping over all elements may seem excessive, it usually performs much faster. On top, in a real world application, you'll end up using more information of the original XML file anyway. – Clayton Louden Oct 14 '12 at 22:35
0

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...

jacques
  • 55
  • 1
  • 6