[英]XPath evaluation with Saxon doesn't work for nodename
為什么以下xpath在Java中用Saxon 9.6不返回任何結果?
//field
奇怪的是,我還對//*
進行了評估,並遍歷了將nodeNames與“ field”進行比較的結果,並為我的文檔獲得了889次匹配。
完整的代碼示例如下:
初始化並運行測試:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
test(doc, "//*");
test(doc, "//field");
測試執行代碼:
private void test(Document doc, String xpathString) throws Exception {
System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl");
XPathFactory xpf;
xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
XPath xpath = xpf.newXPath();
XPathExpression expr = xpath.compile(xpathString);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
int fieldHits = 0;
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
String name = node.getNodeName();
fieldHits = "field".equals(nodes.item(i).getNodeName()) ? fieldHits + 1 : fieldHits;
}
System.out.println("#hits total: " + nodes.getLength());
System.out.println("#hits 'field': " + fieldHits);
}
輸出:
#hits total: 26256
#hits 'field': 889
#hits total: 0
#hits 'field': 0
示例XML文件(感謝wero,我現在知道它與名稱空間有關):
<?xml version="1.0" encoding="UTF-8"?>
<?xfa generator="AdobeLiveCycleDesignerES_V9.0.1.0.20091206.1.615263" APIVersion="3.2.9310.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/" timeStamp="2015-11-17T07:12:49Z" uuid="262c190c-1563-4ae8-ae6e-4c8d59494a3c">
<template xmlns:xliff="urn:oasis:names:tc:xliff:document:1.1" xmlns="http://www.xfa.org/schema/xfa-template/2.8/">
<field name="A"></field>
<field name="B"></field>
<field name="C"></field>
<field name="D"></field>
<field name="E"></field>
<field name="F"></field>
</template>
</xdp:xdp>
最可能的解釋是您的field
元素具有非空名稱空間uri,因此與XPath表達式不匹配。
編輯:
我猜你的文檔聲明了默認的命名空間
xmlns="http://www.xfa.org/schema/xfa-template/2.8/"
因此template
和field
元素位於該命名空間中。
要匹配field
元素,您需要調整 XPath查詢以聲明該名稱空間或僅搜索本地名稱。
請注意,如果要使用s9api接口而不是JAXP,則可以利用XPath 2.0中的功能為XPath表達式中的元素名稱設置默認名稱空間。 您的代碼將如下所示:
private void test(Document doc, String xpathString) throws Exception {
Processor proc = new Processor(false);
XdmNode docNode = proc.newDocumentBuilder().wrap(doc);
XPathCompiler xpath = proc.newXPathCompiler();
xpath.declareNamespace("", "http://www.xfa.org/schema/xfa-template/2.8/");
XdmValue result = xpath.evaluate(xpathString, docNode);
int fieldHits = 0;
for (XdmItem item : result) {
String name = ((XdmNode)node).getNodeName().getLocalName();
fieldHits = "field".equals(name) ? fieldHits + 1 : fieldHits;
}
System.out.println("#hits total: " + nodes.getLength());
System.out.println("#hits 'field': " + fieldHits);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.