简体   繁体   English

如何使用 python ElementTree 获取 XML 中的兄弟标签值

[英]How to get sibling tag values in XML using python ElementTree

I've been trying to get the value of the ci-name element whose sibling RandomAttribute 's value(text) is IMPORTANT.我一直在尝试获取ci-name元素的值,其兄弟RandomAttribute的 value(text) 很重要。 I'm a beginner to python and I'm trying using Python's inbuilt ElementTree.我是 Python 的初学者,我正在尝试使用 Python 的内置 ElementTree。

Here's the sample XML:这是示例 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>

Please help me out with this.这个你能帮我吗。

You can access the value with the XPath-1.0 expression您可以使用 XPath-1.0 表达式访问该值

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

Just put this into a Python XML processor.只需将其放入 Python XML 处理器即可。
In lxml this can look likelxml这看起来像

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

Output should be输出应该是

City 3城市3

Not a solution in one line like the previous one, but I like to keep track of how the XML is structured.不像上一个解决方案在一行中解决,但我喜欢跟踪 XML 的结构。

Maybe this helps you understand how ElementTree works?也许这有助于您了解 ElementTree 的工作原理?

import xml.etree.ElementTree as ET

xml = 'temp.xml'
xmltree = ET.parse(xml)
cities = xmltree.findall('district')[0].findall('city')
for city in cities:
    RandAttribute = city.findall('RandomAttribute')[0].text
    if RandAttribute == "IMPORTANT":
        ci_name = city.findall('ci-name')[0].text
        print(ci_name)
import lxml.etree as etree

if xml you are taking about is string then如果您正在使用的 xml 是字符串,那么

xml_xpath = "/state/district/city[RandomAttribute='IMPORTANT']/ci-name/text()"
XML_dom = etree.XML(xml)
XML_XPATH_name = etree.XPath(xml_xpath)
return XML_XPATH_name(XML_dom)

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

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