如何使用 xmltodict 从 xml 文件中获取项目 [英] How to use xmltodict to get items out of an xml file
问题描述
我正在尝试从 xml 文件中轻松访问值.
<artikel nummer="121"><code>ABC123</code><naam>高亮笔</naam><voorraad>231</voorraad><prijs>0.56</prijs></artikel><artikel nummer="123"><code>PQR678</code><naam>Nietmachine</naam><voorraad>587</voorraad><prijs>9.99</prijs></artikel>..... 等等
如果我想访问值 ABC123,我如何获得它?
导入 xmltodict使用 open('8_1.html') 作为 fd:doc = xmltodict.parse(fd.read())打印(文档[fd]['代码'])
使用您的示例:
导入 xmltodict使用 open('artikelen.xml') 作为 fd:doc = xmltodict.parse(fd.read())
如果你检查 doc
,你会看到它是一个 OrderedDict
,按标签排序:
根节点称为artikelen
,还有一个子节点artikel
,它是一个OrderedDict
对象的列表,所以如果你想要code
对于每篇文章,你会这样做:
codes = []对于 doc['artikelen']['artikelen'] 中的 artikel:代码.附加(文章['代码'])# >>>代码# ['ABC123', 'PQR678']
如果您只在 nummer
为 121
时特别想要 code
,您可以这样做:
code = 无对于 doc['artikelen']['artikelen'] 中的 artikel:如果 artikel['@nummer'] == '121':代码 = artikel['代码']休息
也就是说,如果您正在解析 XML 文档并想要搜索这样的特定值,我会考虑使用 XPath 表达式,由 ElementTree
支持.
I am trying to easily access values from an xml file.
<artikelen>
<artikel nummer="121">
<code>ABC123</code>
<naam>Highlight pen</naam>
<voorraad>231</voorraad>
<prijs>0.56</prijs>
</artikel>
<artikel nummer="123">
<code>PQR678</code>
<naam>Nietmachine</naam>
<voorraad>587</voorraad>
<prijs>9.99</prijs>
</artikel>
..... etc
If i want to acces the value ABC123, how do I get it?
import xmltodict
with open('8_1.html') as fd:
doc = xmltodict.parse(fd.read())
print(doc[fd]['code'])
Using your example:
import xmltodict
with open('artikelen.xml') as fd:
doc = xmltodict.parse(fd.read())
If you examine doc
, you'll see it's an OrderedDict
, ordered by tag:
>>> doc
OrderedDict([('artikelen',
OrderedDict([('artikel',
[OrderedDict([('@nummer', '121'),
('code', 'ABC123'),
('naam', 'Highlight pen'),
('voorraad', '231'),
('prijs', '0.56')]),
OrderedDict([('@nummer', '123'),
('code', 'PQR678'),
('naam', 'Nietmachine'),
('voorraad', '587'),
('prijs', '9.99')])])]))])
The root node is called artikelen
, and there a subnode artikel
which is a list of OrderedDict
objects, so if you want the code
for every article, you would do:
codes = []
for artikel in doc['artikelen']['artikel']:
codes.append(artikel['code'])
# >>> codes
# ['ABC123', 'PQR678']
If you specifically want the code
only when nummer
is 121
, you could do this:
code = None
for artikel in doc['artikelen']['artikel']:
if artikel['@nummer'] == '121':
code = artikel['code']
break
That said, if you're parsing XML documents and want to search for a specific value like that, I would consider using XPath expressions, which are supported by ElementTree
.
这篇关于如何使用 xmltodict 从 xml 文件中获取项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!