Search code examples
pythonxmlstringtagsmapping

How to mapping XML tag by matching the tag with a string using Python?


I have an XML file.

Here is the content:

<Country>
     <number no="2008" info="update">
          <detail name="man1" class="A1">
               <string name="ruth" />
               <string name="amy" />
          </detail>
          <detail name="man2" class="A2">
               <string name="lisa" />
               <string name="graham" />
          </detail>
     </number>
     <number no="2006" info="update">
          <detail name="woman1" class="B1">
               <string name="grace" />
               <string name="chil" />
          </detail>
          <detail name="woman2" class="B2">
               <string name="emy" />
               <string name="toms" />
          </detail>
     </number>
</Country>

I need to get the value of number in here <number no="2008" by mapping with this value class="A1"

I tried this way, but It print None. here is the code:

import xml.etree.ElementTree as ET
ReadXML = ET.parse('data.xml')
stringno = 'A1'
for family in ReadXML.findall('./number/detail[@class="{}"]'.format(stringno)):
    name = family.get('no')
    print(name)

Anyone can help me, please. Thanks a lot


Solution

  • You can use XPath expression to select element number by class attribute of detail child, then you can read no attribute from selected number from python: number[detail/@class="A1"]

    But findall() only supports limited subset of XPath expression which doesn't include the XPath above. We need to resort to a simpler XPath expression, for example using your attempted XPath then selecting parent of matched detail elements using ..:

    stringno = 'A1'
    for family in ReadXML.findall('number/detail[@class="{}"]/..'.format(stringno)):
        name = family.get('no')
        print(name)