0

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>

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.