[英]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 这给了我以下输出:robert lucky Dave
However I am expecting following output Expected Output: robert Dave 但是我期望以下输出预期输出:robert Dave
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
! 实际上获取所有项,然后总是在
a
存在某些东西,然后您尝试从b
获得getAttribute
! why b
? 为什么
b
?
Perhaps last for
is completely not necessary, you can use: 也许最后
for
是完全没有必要的,你可以使用:
student = dom1.getElementsByTagName("sectionA")
And then get attribute with parentNode
! 然后用
parentNode
获取属性!
You can use parentNode()
for example, you can change your code to this: 例如,您可以使用
parentNode()
,您可以将代码更改为此:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.