[英]Read/Extract data from XML with Python
I am trying to read/extract data from XML with Python using xml.etree.ElementTree.我正在尝试使用 xml.etree.ElementTree 使用 Python 从 XML 读取/提取数据。 Unfortunately, up to now, I didn't find how to do it.不幸的是,直到现在,我还没有找到如何去做。 Most probably because I didn't understand how xml works.很可能是因为我不明白 xml 是如何工作的。
The idea is to write the DocumentId number as a list想法是将 DocumentId 编号写为列表
Here is my XML file:这是我的 XML 文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RegisterSearch TotalResults="4">
<SearchResults>
<Document DocumentId="1348828088501913376">
<DocumentNumber>001</DocumentNumber>
</Document>
<Document DocumentId="1348828088501881434">
<DocumentNumber>001</DocumentNumber>
</Document>
<Document DocumentId="1348828088539553420">
<DocumentNumber>010</DocumentNumber>
</Document>
<Document DocumentId="1348828088539570694">
<DocumentNumber>010</DocumentNumber>
</Document>
</SearchResults>
</RegisterSearch>
And here is my Python code:这是我的 Python 代码:
#!/usr/bin/python2
import xml.etree.ElementTree as ET
tree = ET.parse('documents.xml')
root = tree.getroot()
for elem in root:
if(elem.tag=='Document'):
print elem.get('DocumentId')
This is what I try to achieve:这就是我试图实现的目标:
1348828088501913376
1348828088501881434
1348828088539553420
1348828088539570694
Actually, the code brings back nothing...实际上,代码没有带回任何东西......
Thanks in advance for your suggestion.预先感谢您的建议。
Iterate over the tags you are interested in:迭代您感兴趣的标签:
for elem in root.iter(tag='Document'):
print(elem.get('DocumentId'))
Your original solution would work with您的原始解决方案适用于
for elem in root.iter():
...
v3.8: https://docs.python.org/3/library/xml.etree.elementtree.html#finding-interesting-elements v3.8: https ://docs.python.org/3/library/xml.etree.elementtree.html#finding-interesting-elements
v2.7: https://docs.python.org/2.7/library/xml.etree.elementtree.html#finding-interesting-elements v2.7: https : //docs.python.org/2.7/library/xml.etree.elementtree.html#finding-interesting-elements
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.