1

I extract values from XML with namespace using xpath. The XML has namespaces. I find the below local-name a bit complex. Is there a way to achieve the same with a less complex expression? The below example is in Python3 on Ubuntu Linux. I would prefer a generic solution to a specific programming language or environment.

$ cat getname.py 
from lxml import etree
tree = etree.parse("data.xml")
root = tree.getroot()
r = tree.xpath("//*[local-name()='term'][@*[local-name()='id' and .='W08003']]")
for i in r: 
    print (i.text)

$ cat data.xml
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ns2:ucReply xmlns:ns1="http://www.uc.se/schemas/ucOrderRequest/" xmlns:ns2="http://www.uc.se/schemas/ucOrderReply/">
      <ns2:status ns2:result="ok"/>
      <ns2:ucReport>
        <ns2:xmlReply>
          <ns2:reports ns2:lang="swe">
            <ns2:report ns2:index="0">
              <ns2:group ns2:name="ID-uppgifter, fysiker" ns2:key="" ns2:index="0" ns2:id="W080">
                <ns2:term ns2:id="W08001">9550908890</ns2:term>
                <ns2:term ns2:id="W08002">8477362551</ns2:term>
                <ns2:term ns2:id="W08003">Medel Svensson</ns2:term>
                <ns2:term ns2:id="W08004">Högvägen 1</ns2:term>
                <ns2:term ns2:id="W08005">45171</ns2:term>
                <ns2:term ns2:id="W08006">Uddevalla</ns2:term>
                <ns2:term ns2:id="W08018">S</ns2:term>
              </ns2:group>
            </ns2:report>
          </ns2:reports>
        </ns2:xmlReply>
      </ns2:ucReport>
    </ns2:ucReply>
  </soap:Body>
</soap:Envelope>
$ python3 getname.py 
Medel Svensson
$ 

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Andreas F
  • 133
  • 1
  • 8
  • 1
    "Less complex" XPath expressions will result when you define a namespace prefix for each needed namespace and use that rather than defeating namespaces via reference to an element's `local-name()`s. Unfortunately, there is no "generic solution" to specifying namespace-prefix to namespace bindings. See the duplicate link for further details, including library examples for languages such as Python. – kjhughes Jan 12 '20 at 14:52

0 Answers0