Skip to content Skip to sidebar Skip to footer

Parse Xml With Python When Multiple Children Share A Name

I currently have an XML file I am trying to parse. Here is my code thus far. from xml.etree import ElementTree with open('data.xml', 'rt') as f: tree = ElementTree.parse(f) f

Solution 1:

The find method can accept some limited Xpath expressions, you can use this to extract only IPs which are marked as Primary:

from xml.etree import ElementTree
tree = ElementTree.fromstring(sample)

for node in tree.iter('Host'):
    hostname = node.find('Name').text
    ips = node.findall("Networking[Primary='Yes']/IP")
    print hostname
    for ip in ips:
        print ip.text

For further information on what XPath expressions are allowed see the documentation at: https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element


The sample XML provided in the question is malformed in a couple of areas (presumably when it was obfuscated for posting, or the code example given could never have worked). The Type tag is closed twice, and the Primary tags are mismatched with closing Weight tags

Post a Comment for "Parse Xml With Python When Multiple Children Share A Name"