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