Search code examples
pythonxmlminidom

xml.dom.minidom getting elements by tagname


How can I retrieve the value of code with this (below) xml string and when using xml.dom.minidom?

<data>
    <element1>
        <name>myname</name>
    </element1>
    <element2>
        <code>3</code>
        <name>another name</name>
    </element2>
</data>

Because multiple 'name' tags can appear I would like to do something like this:

from xml.dom.minidom import parseString
dom = parseString("<data>...</data>")
dom.getElementsByTagName("element1").getElementsByTagName("name")

But that doesn't work unfortunately.


Solution

  • The below code worked fine for me. I think you had multiple tags and you want to get the name from the second tag.

    myxml = """\
    <data>
        <element>
            <name>myname</name>
        </element>
        <element>
            <code>3</code>
            <name>another name</name>
        </element>
    </data>
    """
    
    dom = xml.dom.minidom.parseString(myxml)
    nodelist = dom.getElementsByTagName("element")[1].getElementsByTagName("name")
    for node in nodelist:
        print node.toxml()