嗨,我正在嘗試讀取定義了命名空間并且一些標簽帶有命名空間的 xml。但是當我使用 XPath 讀取這些標簽時,命名空間標簽總是給出空值。
示例 XML
<?xml version="1.0" encoding="UTF-8"?>
<Employees xmlns:ULAD="http://www.datamodelextension.org/Schema/ULAD">
<EXTENSION>
<OTHER>
<ULAD:HMDAGenderType>Male</ULAD:HMDAGenderType>
</OTHER>
</EXTENSION>
</Employees>
讀取 ULAD:HMDAGenderType 的示例 Java 程式
public static void main(String args[]) throws XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("C:\\test.xml");
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile("/Employees/EXTENSION/OTHER/ULAD:HMDAGenderType");
System.out.println("Gender :: " expr.evaluate(doc, XPathConstants.STRING));
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
輸出::空
預期產出 :: 男性
如何閱讀這些標簽?
uj5u.com熱心網友回復:
嘗試使用 XPathlocal-name()
而不是
XPathExpression expr = xpath.compile("/Employees/EXTENSION/OTHER/ULAD:HMDAGenderType");
請嘗試
XPathExpression expr = xpath.compile("//*[local-name()='HMDAGenderType']");
要直接獲取文本屬性值,您可以使用此 XPath:
XPathExpression expr = xpath.compile("//*[local-name()='HMDAGenderType']/text()");
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/435074.html
上一篇:如何檢查三個值中的兩個是否相同?
下一篇:杰克遜映射到json并改變大小寫
