XML:如何通过属性值获取元素 - Python 2.7 和 minidom
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21427697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XML: How to get Elements by Attribute Value - Python 2.7 and minidom
提问by Martin
I want to get a list of XML Elements based firston TagName and secondon Attribute Value. I′m using the xml.dom library and python 2.7.
我想首先基于 TagName 和第二个基于属性值来获取 XML 元素列表。我正在使用 xml.dom 库和 python 2.7。
While it′s easy to get the first step done:
虽然很容易完成第一步:
from xml.dom import minidom
xmldoc = minidom.parse(r"C:\File.xml")
PFD = xmldoc.getElementsByTagName("PFD")
PNT = PFD.getElementsByTagName("PNT")
I′ve been looking around but cannot find a solution for the second step. Is there something like a .getElementsByAttributeValuethat would give me a list to work with?
我一直在环顾四周,但找不到第二步的解决方案。有没有类似的东西.getElementsByAttributeValue可以给我一份工作清单?
If the XML looks like this
如果 XML 看起来像这样
<PFD>
<PNT A="1" B=.../>
<PNT A="1" B=.../>
<PNT A="2" B=.../>
</PFD>
In need all PNTs where A="1" in a list.
需要列表中 A="1" 的所有 PNT。
采纳答案by Xeun
If you don't find a built-in method, why not iterate over the items?
如果找不到内置方法,为什么不迭代这些项目呢?
from xml.dom import minidom
xmldoc = minidom.parse(r"C:\File.xml")
PFD = xmldoc.getElementsByTagName("PFD")
PNT = xmldoc.getElementsByTagName("PNT")
for element in PNT:
if element.getAttribute('A') == "1":
print "element found"
Adding the items to a list should be easy now.
现在将项目添加到列表应该很容易。
回答by Holly
If you aren't limited to using xml.dom.minidom, lxmlhas better search functionality. Note that lxml is not builtin, and will require installing the lxml packageand non-Python dependencies.
如果您不仅限于使用 xml.dom.minidom,lxml具有更好的搜索功能。请注意,lxml 不是内置的,需要安装lxml 包和非 Python 依赖项。
Eg:
例如:
>>> from lxml import etree
>>> root = etree.parse(r"C:\File.xml")
>>> for e in root.findall('PNT[@A="1"]'):
... print etree.tostring(e)
<PNT A="1" B="c"/>
<PNT A="1" B="b"/>
Lxml also supports all of XPathvia element.xpath('query'). Other convenience functions include element.findtextwhich finds the appropriate element and returns the text of it, element.findand element.findallwhich returns the first/list of all elements matching a query using a subset of XPath covering common queries.
LXML也支持所有的XPath的通过element.xpath('query')。其他方便的函数包括element.findtextwhich 找到适当的元素并返回它的文本,element.find以及element.findall它使用覆盖常见查询的 XPath 子集返回匹配查询的所有元素的第一个/列表。
回答by fcva
Try this:
尝试这个:
from xml.dom import minidom
xmldoc = minidom.parse(r"C:\File.xml")
PNT = xmldoc.getElementsByTagName("PNT")
for element in PNT:
print element.attributes.keys()
for elem in element.attributes.values():
print elem.firstChild.data

