简体   繁体   English

如何获取 Xpath 中的节点值 - Java

[英]how to get a node value in Xpath - Java

I've got a section of XML that looks like this:我有一段 XML 看起来像这样:

<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.我需要从此块中获取链接http://example.com/projects/example1 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.其中children<entry> </entry>块的getChildNodes() object。 But I keep getting NullPointerExceptions when I try to get the node value for the <link> node in a similar way.但是,当我尝试以类似方式获取<link>节点的节点值时,我不断收到NullPointerExceptions I see that the XML code is different for the <link> node, and I'm not sure what it's value is.... Please advise!我看到<link>节点的 XML 代码不同,我不确定它的值是什么......请指教!

The xpath expression to get that node is获取该节点的 xpath 表达式是

//entry/link/@href

In java you can write在 java 你可以写

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然后,如果您需要获取具有特定id的条目的link值,您可以将 xpath 表达式更改为

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

Here is the complete code:这是完整的代码:

    DocumentBuilderFactory domFactory = DocumentBuilderFactory
            .newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("test.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//entry/link/@href");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
         System.out.println(nodes.item(i));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM