如何使用包含Java命名空间的XPath检索XML数据?
我知道这个页面上有很多这样的话题,但很遗憾,我仍然无法找到我的解决方案
以下是我的xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<ns1:Request xmlns:ns1="http://www.sea.com">
<ns1:PayrollRequest>
<ns1:PayrollCost>
<ns1:PayrollID>123</ns1:PayrollID>
<ns1:BatchID>7770</ns1:BatchID>
<ns1:CompanyId>001</ns1:CompanyId>
<ns1:GrossPay>60000</ns1:GrossPay>
</ns1:PayrollCost>
</ns1:PayrollRequest>
</ns1:Request>
这是我用java编写的代码:
import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class XPathTry {
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("SamplePayroll2.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// display all
XPathExpression expr = xpath.compile("//PayrollCost/*/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}
是的,像往常一样,我无法获得输出,因为它只显示:
Process exited with exit code 0.
仅当我删除ns:1时才会显示输出,xml的代码如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<Request xmlns:ns1="http://www.sea.com">
<PayrollRequest>
<PayrollCost>
<PayrollID>123</PayrollID>
<BatchID>7770</BatchID>
<CompanyId>001</CompanyId>
<GrossPay>60000</GrossPay>
</PayrollCost>
</PayrollRequest>
</Request>
问题是,我在网上找到的所有建议似乎都不起作用:
例如,我已经试过了
/*/namespace::*[name()='']
//*[local-name() = 'Element' and namespace-uri() = namespace-uri(/*)]
/*[local-name()=' ']/*[local-name()=' ']/*[local-name()=' ']
etc2
我能得到的唯一最佳输出是,它将显示:
null
有人能给我正确的代码解决我的问题吗
提前谢谢
# 1 楼答案
您必须创建javax.xml.namespace.NamespaceContext的子类,并将其设置为
xpath
:然后可以将名称空间前缀添加到XPath表达式:
# 2 楼答案
XPath表达式需要使用名称空间上下文。你可以阅读更多关于如何做到这一点here