6

我有一段 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块的getChildNodes()对象在哪里<entry> </entry>。但是当我尝试以类似方式NullPointerExceptions获取节点的节点值时,我不断得到。<link>我看到<link>节点的 XML 代码不同,我不确定它的值是什么......请指教!

4

2 回答 2

14

获取该节点的 xpath 表达式是

//entry/link/@href

在java中你可以写

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

然后,如果您需要获取link特定条目的值,id您可以将 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
于 2012-04-10T18:33:23.807 回答
6

这是完整的代码:

    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));
    }
于 2012-04-10T18:41:13.457 回答