如何处理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;
}
}
答案 0 :(得分:1)
与元素内容不同,属性值为normalized。任何空格字符序列(包括'\ n')都将转换为单个ASCII空间,以便进行任何XML处理。因此,实际上,您的XML确实是:
String xml = "<root text=\"hi ho\"> </root>";
另一方面,字符实体未规范化。因此,如果您将该行更改为此,程序应该可以正常工作:
String xml = "<root text=\"hi
ho\"> </root>";