如何使用Java中的XPath获取所有具有文本的节点

时间:2018-11-01 15:34:41

标签: java xml xpath xquery

因此,我对Xpath表达式非常陌生,并将其与Java结合使用。我正在尝试解析XML文件,以使所有节点在标签之间具有一些文本。例如,如果我有XML

<employee>
   <emp>John <age>25</age>
   </emp>
   <salary> 1000
   </salary>
</employee>

那我应该得到

  

约翰25 1000

,即,任何标签之间仅包含文本内容,而不会重复。  我在这里遵循此tutorial,以使用Xpath表达式获取所需的值。 我写了以下代码段:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;;

public class xpathTest {

public static void main(String[] args) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("TestXmlFile.xml");

    //Create XPath

    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();

    XPathExpression expr = xpath.compile("//*[text()]"); // to get all all nodes having some text

    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).getNodeValue());

    }
}

此代码面临的问题是它仅返回 null 值,而不是这些文本值。您能在这里发现我做错了吗?

0 个答案:

没有答案