我的 XML 看起来像这样
<TOPIC>
<LIST>
<Area>JKH</Area>
<USED>
<type id='123' />
<type id='345' />
</USED>
<DEMAND>
<type id='809' />
<type id='321' />
</DEMAND>
<CLOSED>
<type id='456' />
<type id='765' />
</CLOSED>
</LIST>
</TOPIC>
这里我只想打印
id
下的<DEMAND>
。我试过下面的代码。
from xml.dom import minidom
root=minidom.parse('sample.xml')
tag=root.getElementsByTagName('type')
for i in tag:
print(i.getAttribute("id"))
但是这是打印所有
id
值,如下所示。
123
345
809
321
456
765
我怎样才能只获得
809
标签下的321
和<DEMAND>
。我可以在 ElementTree
中给出路径,但不确定如何在 getElementsByTagName
中让步?在 Minidom 中甚至可能吗?
for demand in root.getElementsByTagName('DEMAND'):
for tp in demand.getElementsByTagName('type'):
print(tp.getAttribute("id"))