我的xpath查询不起作用,我找不到几个小时的解决方案 . 我感谢你的每一个帮助 .
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource inputSource = new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")));
Document xmldocument = db.parse(inputSource);
XPath xPath = XPathFactory.newInstance().newXPath();
String prefix = xmldocument.getDocumentElement().getPrefix();
searchElementsXml = new String[]{"name", "id", "version", "description", "keywords", "authorInfos.name", "status"};
for(int j = 0; j < searchElementsXml.length; j++){
String expression ="/*/" + prefix + ":" + searchElementsXml[j];
NodeList nodeList = (NodeList)
xPath.compile(expression).evaluate(xmldocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
}
以前尝试表达的部分内容:
String expression ="/*/" + prefix + ":" + searchElementsXml[j];
String expression ="/*:serviceSpecification" "/*:" + searchElementsXml[j];
String expression ="/*/*:id"
它们在https://www.freeformatter.com/xpath-tester.html#ad-output上工作,但在我的java代码中没有 .
我的XML看起来像:
<?xml version="1.0" encoding="UTF-8"?>
<ServiceSpecificationSchema:serviceSpecification xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ServiceSpecificationSchema="http://foo.bar/ServiceSpecificationSchema.xsd" xsi:schemaLocation="http://foo.barServiceSpecificationSchema.xsd ServiceSpecificationSchema.xml">
<ServiceSpecificationSchema:id>someid</ServiceSpecificationSchema:id>
<ServiceSpecificationSchema:name>myname</ServiceSpecificationSchema:name>
....
2 回答
我有以下几行:
绝对不知道为什么这有效,但现在我的查询工作 .
一般来说,它取决于您使用的基础XPath引擎和XPath版本,但实际上:
String expression ="/*/" + prefix + ":" + searchElementsXml[j];
如果
prefix
与NamespaceContext中设置的名称空间URI不匹配,则不会返回结果 . 所以在你设置它之后 - 它有效 .String expression ="/*:serviceSpecification" "/*:" + searchElementsXml[j];
以及
String expression ="/*/*:id"
两者都定义必须为任何名称空间检索
serviceSpecification
和id
(或searchElementsXml[j]
) . - 属于XPath引擎和版本 - 如果它受支持那么它的工作原理 .注意:XPath 1.0不支持"any namespace"为
/*:element
. XPath 2 . 因此,也许您使用的引擎会将XPath表达式威胁为XPath 1.0