簡體   English   中英

如何獲取 Xpath 中的節點值 - Java

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

我有一段 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>

我需要從此塊中獲取鏈接http://example.com/projects/example1 我不知道該怎么做。 要獲得項目的標題,我使用以下代碼:

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

其中children<entry> </entry>塊的getChildNodes() object。 但是,當我嘗試以類似方式獲取<link>節點的節點值時,我不斷收到NullPointerExceptions 我看到<link>節點的 XML 代碼不同,我不確定它的值是什么......請指教!

獲取該節點的 xpath 表達式是

//entry/link/@href

在 java 你可以寫

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

然后,如果您需要獲取具有特定id的條目的link值,您可以將 xpath 表達式更改為

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

最后如果你想獲取文檔中的所有鏈接,如果文檔有很多入口元素你可以這樣寫

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

這是完整的代碼:

    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