python minidom xml解析器3

时间:2017-06-20 12:02:07

标签: python xml parsing minidom

<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

这给了我以下输出:     罗伯特     幸运     戴夫

但是我期待以下输出 预期产出: 罗伯特 戴夫

1 个答案:

答案 0 :(得分:0)

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