如何让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代码是不同的,我不确定它的价值是什么....请指教!

+0

你需要为这个XPath语法?或者您需要Java API语法? – 2012-04-10 18:31:28

+1

啊,好的问题,寻找Java API的语法。但我明白了,看下面。谢谢 – blaughli 2012-04-10 19:01:13

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 
+1

谢谢你,你把我推向了正确的方向。使用您提供的语法,我可以评估编译的Xpath表达式(将结果作为“NODESET”返回)。然后,我从结果(NODESET)中创建了一个NodeList,然后用一个while循环遍历所有来自我正在阅读的RSS页面的链接。非常感谢你 :)。 – blaughli 2012-04-10 19:03:59

+0

我也向答案添加了'NodeList'示例。为了完整性。 – dash1e 2012-04-10 19:10:28

下面是完整的代码:

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