简体   繁体   中英

parsing XML in python by using xml.etree.ElementTree

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>

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

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

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