Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a node value in Xpath - Java

I've got a section of XML that looks like this:

<entry>
<id>tag:example.com,2005:Release/343597</id>
<published>2012-04-10T11:29:19Z</published>
<updated>2012-04-10T12:04:41Z</updated>
<link type="text/html" href="http://example.com/projects/example1" rel="alternate"/>
<title>example1</title>
</entry>

I need to grab the link http://example.com/projects/example1 from this block. I'm not sure how to do this. To get the title of the project I use this code:

String title1 = children.item(9).getFirstChild().getNodeValue();

where children is the getChildNodes() object for the <entry> </entry> block. But I keep getting NullPointerExceptions when I try to get the node value for the <link> node in a similar way. I see that the XML code is different for the <link> node, and I'm not sure what it's value is.... Please advise!

like image 1000
blaughli Avatar asked Apr 10 '12 18:04

blaughli


1 Answers

The xpath expression to get that node is

//entry/link/@href

In java you can write

Document doc = ... // your XML document
XPathExpression xp = XPathFactory.newInstance().newXPath().compile("//entry/link/@href");
String href = xp.evaluate(doc);

Then if you need to get the link value of the entry with a specific id you can change the xpath expression to

//entry[id='tag:example.com,2005:Release/343597']/link/@href

Finally if you want to get all the links in the documents, if the document has many entry elements you can write

Document doc = ... // your XML document
XPathExpression xp = XPathFactory.newInstance().newXPath().compile("//entry/link/@href");
NodeList links = (NodeList) xp.evaluate(doc, XPathConstants.NODESET);
// and iterate on links
like image 125
dash1e Avatar answered Oct 20 '22 15:10

dash1e