繁体   English   中英

使用XPath从XML获取元素值

[英]Get element value from XML with XPath

我有这样的XML文件:

<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents- xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 UBL-Invoice-2.1.xsd">
<cac:AccountingSupplierParty>
<cac:Party>
  <cac:PartyIdentification>
    <cbc:ID schemeID="schema1">123231123</cbc:ID>
  </cac:PartyIdentification>
  <cac:PartyIdentification>
    <cbc:ID schemeID="schema2">2323232323</cbc:ID>
  </cac:PartyIdentification>
  <cac:PartyIdentification>
    <cbc:ID schemeID="schema3">4442424</cbc:ID>
  </cac:PartyIdentification>
  <cac:PostalAddress>
    <cbc:CityName>İstanbul</cbc:CityName>
    <cac:Country>
      <cbc:Name>Turkey</cbc:Name>
    </cac:Country>
  </cac:PostalAddress>
</cac:Party>
</cac:AccountingSupplierParty>
</Invoice>

我想访问schemeID =“schema = 2”值。 我尝试XPath和document.getElementsByTagName。 我可以使用document.getElementsByTagName访问元素,因为是多个我无法访问我想要的元素。 当我尝试使用XPath时,我无法访问XML中的任何元素。

这是我的XPath实现:

try {
    String decoded = new 
    String(DatatypeConverter.parseBase64Binary(binaryXmlData));
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(decoded));
    Document doc = db.parse(is);
    String expression = "/Invoice/cac:AccountingSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID@[schemaID='schema2']/text()";    
    String schema2 = (String) xPath.compile(expression).evaluate(doc, XPathConstants.STRING);
    System.out.println(schema2);
    //schema2 is null

    //Above this code block returns correct value
    NodeList nl = doc.getElementsByTagName("cbc:CityName");
    System.out.println(nl.item(0).getTextContent());

} catch () {

}

binaryXmlData是我的XML的源代码。 首先,我将base64binary数据转换为xml。 我在转换错误或我的xpath实现是错误的吗?

您的代码和XML存在许多问题,包括:

  1. 您的XML格式不正确。 缺少cbc名称空间前缀的结束引号。
  2. 您的Java代码永远不会定义NamespaceContext

另请参见XPath如何处理XML命名空间?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM