XPathExpression Evaluate 在 java 中返回一个空的 NodeList



我试图从标签中获取值属性:

<pip:property name="release-name" value="2018 November Release"/>

我的 xml 是:

<pip:object-group id="id-6b940c81-ed37-45ec-ac85-68ae13a6c6a0" target-object-uri="http://doc.test.com/us/hlrp/topic/c64a80ee742330778d018b0505cda195">
<pip:properties>
<pip:property name="release-name" value="2018 November Release"/>
</pip:properties>
<pip:store id="id-93379bb2-e837-42b9-8316-aef393f1e034" object-uri="http://doc.test.com/us/hlrp/topic/c64a80ee742330778d018b0505cda195.htm" aspect="content" path="documents/c64a80ee742330778d018b0505cda195/c64a80ee742330778d018b0505cda195.htm"/>
<pip:store id="id-99a5d375-2084-4f82-b30c-c932bb4bbb31" object-uri="http://doc.test.com/us/hlrp/topic/c64a80ee742330778d018b0505cda195.rdf" aspect="metadata" path="documents/c64a80ee742330778d018b0505cda195/meta.rdf"/>
</pip:object-group>

我在 Java 中获取价值的方法是:

private String getReleaseFolder(String manifestFolder, String procedureId) throws Exception {

String releaseFolder = new String();
XPathExpression expr;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = (Document) builder.parse(manifestFolder);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();

xpath.setNamespaceContext(new NamespaceContext() {    //minimalist
public String getNamespaceURI(String prefix) {
if (prefix.equals("pip")) {
getLogger().info("I am in the first branch");
return "http://schema.wolterskluwer.com/pci/interface-protocol-v4.0/";
}
if (prefix.equals("xsi")){
getLogger().info("I am in the second branch");
return "http://www.w3.org/2001/XMLSchema-instance";
} else {
getLogger().info("I am in the third branch");
return null;
}
}
public String getPrefix(String namespaceURI) {
return null;
}
public Iterator<String> getPrefixes(String namespaceURI) {
return null;
}
});

expr = xpath.compile("//pip:properties[following-sibling::pip:store[contains(@path,"" + procedureId +"")]]/pip:property[@name="release-name"]/@value");     
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
if (nl.getLength() == 0) {
String emailBody = CsbConstants.EMAILBODY_MANIFEST + procedureId + CsbConstants.EMAILBODY_MANIFEST_PART;
getLogger().info(emailBody);
// here we send an email
// here we throw a new Exception
Exception e = new Exception(emailBody);
throw e;
}
releaseFolder = nl.item(0).getNodeValue();

return releaseFolder;
}

但是,我的 NodeList: nl.getLength(( 是 0。你能帮忙吗?提前谢谢你。

你需要告诉你的 DocumentBuilderFactory 解析命名空间:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);

最新更新