简体   繁体   中英

Get element value from XML with XPath

I have XML file like this:

<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>

I want to access schemeID="schema=2" value. I try XPath and document.getElementsByTagName. I can access elements with document.getElementsByTagName, since is multiple I can't access the element I want. When I try to with XPath, I can't access any elements from XML.

Here is my XPath implementation:

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 is source of my XML. First, I convert base64binary data to xml. Am I doing to convertion wrong or my xpath implementation is wrong ?

There are many problems with your code and your XML, including:

  1. Your XML is not well-formed. The closing quote of the cbc namespace prefix is missing.
  2. Your Java code never defines a NamespaceContext .

See also How does XPath deal with XML namespaces?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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