Home > other >  parsing XML in python by using xml.etree.ElementTree
parsing XML in python by using xml.etree.ElementTree

Time:12-16

I get an XML file using the request module, then I want to use the xml.etree.ElementTree module to get the output of the element core-usg-01 but I'm already confused how to do it, im stuck. I tried writing this simple code to get the sysname element, but I get an empty output. Python code:

import xml.etree.ElementTree as ET

tree = ET.parse('usg.xml')
root = tree.getroot()
print(root.findall('sysname'))

XML file:

<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1">
    <data>
        <system-state xmlns="urn:ietf:params:xml:ns:yang:ietf-system">
            <sysname xmlns="urn:huawei:params:xml:ns:yang:huawei-system">
                core-usg-01
            </sysname>
        </system-state>
    </data>
</rpc-reply>

CodePudding user response:

You need to iter() over the root to reach to the child.

for child in root.iter():
   print (child.tag, child.attrib)

Which will give you the present children tags and their attributes.

{urn:ietf:params:xml:ns:netconf:base:1.0}rpc-reply {'message-id': '1'}
{urn:ietf:params:xml:ns:netconf:base:1.0}data {}
{urn:ietf:params:xml:ns:yang:ietf-system}system-state {}
{urn:huawei:params:xml:ns:yang:huawei-system}sysname {}

Now you need to loop to your desired tag using following code:

for child in root.findall('.//{urn:ietf:params:xml:ns:yang:ietf-system}system-state'):
    temp = child.find('.//{urn:huawei:params:xml:ns:yang:huawei-system}sysname')
    print(temp.text)

The output will look like this:

core-usg-01

CodePudding user response:

Try the below one liner

import xml.etree.ElementTree as ET


xml = '''<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1">
    <data>
        <system-state xmlns="urn:ietf:params:xml:ns:yang:ietf-system">
            <sysname xmlns="urn:huawei:params:xml:ns:yang:huawei-system">
                core-usg-01
            </sysname>
        </system-state>
    </data>
</rpc-reply>'''

root = ET.fromstring(xml)
print(root.find('.//{urn:huawei:params:xml:ns:yang:huawei-system}sysname').text)

output

core-usg-01
  • Related