gpt4 book ai didi

Python XML 到字典以迭代项目

转载 作者:数据小太阳 更新时间:2023-10-29 02:02:39 26 4
gpt4 key购买 nike

我有以下 XML 示例

<?xml version="1.0"?>
<test>
<items>
<item>item 1</item>
<item>item 2</item>
</items>
</test>

我需要在 python 中的 for 循环中遍历每个标记。如果尝试了很多东西,但我就是做不到......

感谢帮助

最佳答案

我个人使用xml.etree.cElementTree ,因为我发现它工作得很好,速度很快,easy to use , 和 works well with big (>2GB) files .

import xml.etree.cElementTree as etree

with open(xml_file_path) as xml_file:
tree = etree.iterparse(xml_file)
for items in tree:
for item in items:
print item.text

在交互式控制台中

>>> x="""<?xml version="1.0"?>
<test>
<items>
<item>item 1</item>
<item>item 2</item>
</items>
</test>"""
>>> x
'<?xml version="1.0"?>\n<test>\n <items>\n <item>item 1</item>\n <item>item 2</item>\n </items>\n</test>'
>>> import xml.etree.cElementTree as etree
>>> tree = etree.fromstring(x)
>>> tree
<Element 'test' at 0xb63ad248>
>>> for i in tree:
for j in i:
print j


<Element 'item' at 0xb63ad2f0>
<Element 'item' at 0xb63ad338>
>>> for i in tree:
for j in i:
j.text

'item 1'
'item 2'
>>>

关于Python XML 到字典以迭代项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2372217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com