如何让Xpath的节点值 - Java的
问题描述:
我有XML的部分看起来像这样:如何让Xpath的节点值 - Java的
<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()
对象。但是当我尝试以类似的方式获取<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
最后if你想获得的文件的所有链接,如果文件有许多项元素,你可以写
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));
}
+0
谢谢Phani,那正是我所做的。 – blaughli 2012-04-10 19:08:46
你需要为这个XPath语法?或者您需要Java API语法? – 2012-04-10 18:31:28
啊,好的问题,寻找Java API的语法。但我明白了,看下面。谢谢 – blaughli 2012-04-10 19:01:13