繁体   English   中英

python 通过路径获取 xml 元素

[英]python get xml element by path

我尝试浏览一个大型 xml 文件,并收集一些数据。 由于可以通过路径找到数据的位置,所以我使用了xpath,但没有结果。

有人可以建议我做错了什么吗?

xml 示例:

<?xml version="1.0" encoding="UTF-8"?>
<rootnode>
    <subnode1>

    </subnode1>
    <subnode2>

    </subnode2>
    <subnode3>
        <listnode>
            <item id="1"><name>test name1</name></item>
            <item id="2"><name>test name2</name></item>
            <item id="3"><name>test name3</name></item>
        </listnode>
    </subnode3>
</rootnode>

编码:

import lxml.etree as ET

tree = ET.parse('temp/temp.xml')

subtree = tree.xpath('./rootnode/subnode3/listnode')

for next_item in subtree:
    Id = next_item.attrib.get('id')
    name = next_item.find('name').text
    print('{:>20} - {:>20}'.format(name,Id))

你很接近。

前任:

import lxml.etree as ET

tree = ET.parse('temp/temp.xml')

subtree = tree.xpath('/rootnode/subnode3/listnode')
for next_item in subtree:
    for item in next_item.findall('item'):
        Id = item.attrib.get('id')
        name = item.find('name').text
        print('{:>20} - {:>20}'.format(name,Id))

或者

subtree = tree.xpath('/rootnode/subnode3/listnode/item')
for item in subtree:
    Id = item.attrib.get('id')
    name = item.find('name').text
    print('{:>20} - {:>20}'.format(name,Id))  

Output:

  test name1 -                    1
  test name2 -                    2
  test name3 -                    3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM