我在XML中有很多行,我试图获得一个特定节点属性的实例。
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
我如何访问属性foobar的值?在这个例子中,我想要“1”和“2”。
我在XML中有很多行,我试图获得一个特定节点属性的实例。
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
我如何访问属性foobar的值?在这个例子中,我想要“1”和“2”。
当前回答
simplified_scrapy:一个新的库,我使用后就爱上了它。我向你推荐。
from simplified_scrapy import SimplifiedDoc
xml = '''
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
'''
doc = SimplifiedDoc(xml)
types = doc.selects('bar>type')
print (len(types)) # 2
print (types.foobar) # ['1', '2']
print (doc.selects('bar>type>foobar()')) # ['1', '2']
这里有更多的例子。这个库很容易使用。
其他回答
Python有一个到expat XML解析器的接口。
xml.parsers.expat
它是一个非验证解析器,因此不会捕获糟糕的XML。但如果你知道你的文件是正确的,那么这就很好了,你可能会得到你想要的确切信息,你可以丢弃其余的。
stringofxml = """<foo>
<bar>
<type arg="value" />
<type arg="value" />
<type arg="value" />
</bar>
<bar>
<type arg="value" />
</bar>
</foo>"""
count = 0
def start(name, attr):
global count
if name == 'type':
count += 1
p = expat.ParserCreate()
p.StartElementHandler = start
p.Parse(stringofxml)
print count # prints 4
为了增加另一种可能性,可以使用untangle,因为它是一个简单的xml-to-python-object库。这里有一个例子:
安装:
pip install untangle
用法:
你的XML文件(有一点变化):
<foo>
<bar name="bar_name">
<type foobar="1"/>
</bar>
</foo>
使用untangle访问属性:
import untangle
obj = untangle.parse('/path_to_xml_file/file.xml')
print obj.foo.bar['name']
print obj.foo.bar.type['foobar']
输出将是:
bar_name
1
更多关于untangle的信息可以在“untangle”中找到。
此外,如果您感兴趣,可以在“Python和XML”中找到使用XML和Python的工具列表。您还将看到前面的答案中提到的最常见的问题。
如果源文件是一个xml文件,就像这个示例一样
<pa:Process xmlns:pa="http://sssss">
<pa:firsttag>SAMPLE</pa:firsttag>
</pa:Process>
您可以尝试下面的代码
from lxml import etree, objectify
metadata = 'C:\\Users\\PROCS.xml' # this is sample xml file the contents are shown above
parser = etree.XMLParser(remove_blank_text=True) # this line removes the name space from the xml in this sample the name space is --> http://sssss
tree = etree.parse(metadata, parser) # this line parses the xml file which is PROCS.xml
root = tree.getroot() # we get the root of xml which is process and iterate using a for loop
for elem in root.getiterator():
if not hasattr(elem.tag, 'find'): continue # (1)
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i+1:]
dict={} # a python dictionary is declared
for elem in tree.iter(): #iterating through the xml tree using a for loop
if elem.tag =="firsttag": # if the tag name matches the name that is equated then the text in the tag is stored into the dictionary
dict["FIRST_TAG"]=str(elem.text)
print(dict)
输出将是
{'FIRST_TAG': 'SAMPLE'}
xml.etree.ElementTree vs. lxml
下面是两个最常用的库的一些优点,在进行选择之前,我应该了解它们。
xml.etree.ElementTree:
来自标准库:不需要安装任何模块
lxml
轻松编写XML声明:例如,您是否需要添加standalone="no"? 漂亮的打印:无需额外代码就可以得到漂亮的缩进XML。 Objectify功能:它允许您像处理普通的Python对象hierarchy.node一样使用XML。 sourceline允许您轻松地获取正在使用的XML元素的行。 您还可以使用内置的XSD模式检查器。
Minidom是最快速且非常直接的方法。
XML:
<data>
<items>
<item name="item1"></item>
<item name="item2"></item>
<item name="item3"></item>
<item name="item4"></item>
</items>
</data>
Python:
from xml.dom import minidom
dom = minidom.parse('items.xml')
elements = dom.getElementsByTagName('item')
print(f"There are {len(elements)} items:")
for element in elements:
print(element.attributes['name'].value)
输出:
There are 4 items:
item1
item2
item3
item4