我一直在尝试获取ci-name元素的值,该元素的同级RandomAttribute的value(text)是重要的。我是python的初学者,正在尝试使用Python的内置ElementTree。

这是示例XML:

<state>
    <s-name>State 1</s-name>
    <district>
        <d-name>District 1</d-name>
        <city>
            <ci-name>City 1</ci-name>
            <RandomAttribute>UN- IMPORTANT</RandomAttribute>
        </city>
        <city>
            <ci-name>City 2</ci-name>
            <RandomAttribute>NOT SO IMPORTANT</RandomAttribute>
        </city>
        <city>
            <ci-name>City 3</ci-name>
            <RandomAttribute>IMPORTANT</RandomAttribute>
        </city>
    </district>
</state>


这个你能帮我吗。

最佳答案

您可以使用XPath-1.0表达式访问该值

/state/district/city[RandomAttribute='IMPORTANT']/ci-name


只需将其放入Python XML处理器即可。
lxml中,它看起来像

xml = ...
tree = etree.parse(xml)
result = tree.xpath('/state/district/city[RandomAttribute='IMPORTANT']/ci-name')
print(result[0].tag)


输出应为


城市3

关于python - 如何使用python ElementTree获取XML中的同级标记值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59094610/

10-12 21:58
查看更多