XPath Java对指定命名空间的文档使用双斜杠计算表达式
以下是一些Java代码:XPath Java对指定命名空间的文档使用双斜杠计算表达式,java,xml,xpath,namespaces,Java,Xml,Xpath,Namespaces,以下是一些Java代码: import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XpathQuestion {
public static void main(String[] args) throws SAXException, IOException, XPathExpressionException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
XPath xpath = XPathFactory.newInstance().newXPath();
File xmlFile = new File("stackoverflow.xml");
Document doc = documentBuilder.parse(new InputSource(xmlFile.getAbsolutePath()));
NodeList nodes1 = (NodeList) (xpath.evaluate("//AB", doc,
XPathConstants.NODESET));
NodeList nodes2 = (NodeList) (xpath.evaluate("//AB/stat", doc,
XPathConstants.NODESET));
int nodes1Length = nodes1.getLength();
int nodes2Length = nodes2.getLength();
System.out.println(nodes1Length);
System.out.println(nodes2Length);
}
}
上述代码中的文档stackoverflow.xml如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<ns:document xmlns:ns="http://www.noinfohere.de">
<ns:env>
<ns:trans>
<ns:version>123</ns:version>
</ns:trans>
<ns:sender>
<ns:senderId>abc</ns:senderId>
</ns:sender>
</ns:env>
<ns:AB>
<ns:stat>asdf</ns:stat>
</ns:AB>
</ns:document>
平均值:节点1长度=0和
节点2长度=1
我不明白的是:为什么nodes1Length=0?xpath表达式“//AB”应该找到文档中的所有AB元素。我的程序怎么了
Thanx 4您的帮助。文档中没有
AB
元素,可能存在重复项。它们是{http://www.noinfohere.de}AB
元素。请查看上面的链接。@JLRishe实际上,由于代码调用了factory.setNamespaceAware(false)
,文档可能包含全名为ns:AB
的元素。
0
1