0

I tried to search xml file, using xpath, with code:

import xml.etree.ElementTree as ET

tree = ET.parse('example.xml')
root = tree.getroot()

for node in root.findall('.//call/moc/digit'):
   print("node: ", node.text)

I got :

node:  398
node:  3989

But if the xml file has attribute for call, , then the code finds nothing. I also tried with

root.findall('.//call[@xmlns=test]')

which also fails.

The exmple.xml:

<data>
  <call>   // If I have <call xmlns="test">, the code found nothing, why? 
    <moc>
      <name>0</name>
      <instance>
        <code>11</code>
      </instance>
      <digit>398</digit>
      <number>100</number>
    </moc>

    <moc>
      <name>1</name>
      <instance>
        <code>110</code>
      </instance>
      <digit>3989</digit>
      <number>1000</number>
    </moc>
  </call>
  <count>900</count>
</data>

Thank you for any suggestions in advance.

issac
  • 155
  • 8
  • 1
    It's defining a namespace and you need to [work with it](https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces) – Chillie Jun 23 '21 at 21:25
  • @Chillie, thank you very much for pointing it out. – issac Jun 23 '21 at 21:30
  • 1
    If all you want to do is read/process the xml (i.e. not modify and write it out including source namespaces) then you can remove namespaces when reading the xml and generally (assuming no conflicting tag names) make it easier to work with your xml. See answers by nonagon and extended by me here https://stackoverflow.com/questions/34082582/python-ignoring-namespaces-in-xml-etree-elementtree/34084066#34084066 – DisappointedByUnaccountableMod Jun 23 '21 at 22:08

0 Answers0