如何避免在xpath节点之间返回空格和行返回?

时间:2015-05-04 14:07:47

标签: java xml xpath

我正在尝试学习使用Java xpath,但遇到了一个问题。当我使用getNodeName和getTextContent时,我最终抓住节点之间发生的空白和行返回。例如,如果我的XML看起来像:

<node-i-am-looking-for-in-my-xml>
    <parent-node-01>
        <child-node-01>
            some text
        </child-node>
        <child-node-02>
            some more text
        </child-node>
        <child-node-03>
            even more text
        </child-node>
    </parent-node-01>
    <parent-node-02>
        <child-node-01>
            some text
        </child-node>
        <child-node-02>
            some more text
        </child-node>
        <child-node-03>
            even more text
        </child-node>
    </parent-node-02>
    <parent-node-03>
        <child-node-01>
            some text
        </child-node>
        <child-node-02>
            some more text
        </child-node>
        <child-node-03>
            even more text
        </child-node>
    </parent-node-03>
</node-i-am-looking-for-in-my-xml>

使用getNodeName时得到的结果如下:

child-node-01
#text
child-node-02
#text
child-node-03
#text

当我使用getTextContent时,它看起来像:

some text

some more text

even more text

这是我正在使用的代码:

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    String filename = "C:\\Users\\Me\\file.xml";
    Document doc = db.parse(new FileInputStream(new File(filename)));
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    String expression;
    Node node;
    NodeList nodeList;

    expression = "//node-i-am-looking-for/*";
    nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
    System.out.println("nodeList.getLength(): " + nodeList.getLength());
    for (int i = 0; i < nodeList.getLength(); i++) {
        for(int j=1; j<(nodeList.item(i).getChildNodes().getLength()); j++){
            Node nowNode = nodeList.item(i).getChildNodes().item(j);
            System.out.println(nowNode.getNodeName() + ":" + nowNode.getTextContent());
        }
    }
}

在浏览Google时,似乎我需要使用&#34; normalize-space&#34;,但我无法弄清楚如何实现它。

1 个答案:

答案 0 :(得分:0)

如您所见,空白在XML文本节点中很重要。 child-node-01的文本内容(或更确切地说,父文件为child-node-01的文本节点的内容)实际为'\n some text\n '

如果需要在XPath表达式中处理这个空格,则只能使用normalize-space,因为normalize-space是一个XPath函数。例如,如果要选择文本内容(删除前导/尾随空格)为'some data'的所有节点,则可以使用类似的XPath:

//*[normalize-space(.) = 'some data']

但是当您检索到文本内容时,您已经在XPath世界之外,并且回到Java中,所以您可能会更好:

nowNode.getTextContent().trim()