Search code examples
pythonxmlparsingminidom

python minidom xml parser 3


<student id="1" student:name="robert">
 <sectionA>
  <class name="first"/>
 </sectionA>
</student>
<student id="2" student:name="lucky">
 <sectionB>
  <class name="first"/>
 </sectionB>
</student>
<student id="2" student:name="Dave">
 <sectionA>
  <class name="third"/>
 </sectionA>
</student>


from xml.dom import minidom

dom1 = minidom.parse("file.xml")
student = dom1.getElementsByTagName("student")
for b in student:
    sectionA = dom1.getElementsByTagName("sectionA")
    for a in sectionA:
        name = b.getAttribute("student:name")
        print name

This gives me the following output: robert lucky Dave

However I am expecting following output Expected Output: robert Dave


Solution

  • In this line:

    student = dom1.getElementsByTagName("student")
    

    Actually get all items and then always something exists in a, then you tried to getAttribute from b! why b?

    Perhaps last for is completely not necessary, you can use:

    student = dom1.getElementsByTagName("sectionA")
    

    And then get attribute with parentNode!

    You can use parentNode() for example, you can change your code to this:

    from xml.dom import minidom
    
    dom1 = minidom.parse("file.xml")
    student = dom1.getElementsByTagName("sectionA")
    
    for b in student:
      print(b.parentNode.getAttribute("name"))
    
    # Output:
    # robert
    # Dave
    

    Ref: xml.de