Java - 如何通过包含新行的属性值进行选择

时间:2014-12-23 21:35:37

标签: java xpath newline

如何处理XPath查询中的新行字符?

以下失败:

public class XPathWithNewLine {
    public static void main(String[] args) {
        String xml = "<root text=\"hi\nho\"> </root>";
        String xpathStr = "//*[@text='hi\nho']";

        NodeList list = eval(xml, xpathStr);
        if (list != null && list.getLength() > 0) {
            System.out.println(list.item(0).getNodeName());
        } else {
            System.err.println("Failed!");
        }
    }

    public static NodeList eval(String xml, String xpathStr) {
        XPath xpath = XPathFactory.newInstance().newXPath();

        InputSource source = new InputSource(new StringReader(xml));

        NodeList nodeList = null;
        try {
            nodeList = (NodeList) xpath.compile(xpathStr).evaluate(source, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        return nodeList;
    }
}

1 个答案:

答案 0 :(得分:1)

与元素内容不同,属性值为normalized。任何空格字符序列(包括'\ n')都将转换为单个ASCII空间,以便进行任何XML处理。因此,实际上,您的XML确实是:

String xml = "<root text=\"hi ho\"> </root>";

另一方面,字符实体未规范化。因此,如果您将该行更改为此,程序应该可以正常工作:

String xml = "<root text=\"hi&#xa;ho\"> </root>";