【问题标题】:How to test if an XML node has a specific string using Element Tree如何使用元素树测试 XML 节点是否具有特定字符串
【发布时间】:2017-12-04 03:17:46
【问题描述】:

我目前正在使用元素树来解析一些 XML,其中一些具有多个重复的名称/值对,看起来像这样。我想要做的是提取感兴趣的元素,即性别 = 男性和颜色 = 红色,但由于结构的原因,我似乎无法单独使用 findall 来做到这一点。 如何提取这些元素?我认为正确的逻辑是寻找一个可以找到 child.text = 'gender' 等的子节点,然后继续打印该子节点的名称/值。最好的方法是什么?

<a:characteristic>
    <name>gender</name>
    <value>male</value>
</a:characteristic>
<a:characteristic>
    <name>age</name>
    <value>30</value>
</a:characteristic>
<a:characteristic>
    <name>colour</name>
    <value>red</value>
</a:characteristic>
<a:characteristic>
    <name>language</name>
    <value>python</value>
</a:characteristic>         

【问题讨论】:

    标签: python xml key-value


    【解决方案1】:

    我不会尝试处理 XML 文档结构来进行这种查询,我会制作一个更方便的数据结构来根据这种特性进行查询 - 字典以特征名作为键,以特征值作为值

    类似:

    import xml.etree.ElementTree as ET
    
    data = """<root xmlns:a="http://www.w3.org/2002/07/a#">
        <a:characteristic>
            <name>gender</name>
            <value>male</value>
        </a:characteristic>
        <a:characteristic>
            <name>age</name>
            <value>30</value>
        </a:characteristic>
        <a:characteristic>
            <name>colour</name>
            <value>red</value>
        </a:characteristic>
        <a:characteristic>
            <name>language</name>
            <value>python</value>
        </a:characteristic>        
    </root>"""
    
    namespaces = {'a': 'http://www.w3.org/2002/07/a#'} 
    root = ET.fromstring(data)
    characteristics = {
        item.findtext("name"): item.findtext("value")
        for item in root.findall('a:characteristic', namespaces)
    }
    print(characteristics)
    

    打印:

    {'gender': 'male', 'age': '30', 'colour': 'red', 'language': 'python'}
    

    现在,获取gender 值就像characteristics['gender'] 一样简单。

    【讨论】:

    • 除了 alecxe 有助于将数据转换为更方便的通用形式之外,还要注意对 findall() 的命名空间声明参数的正确使用,这很可能会挫败任何个人 findall() 尝试OP的原始代码。
    猜你喜欢
    • 2013-01-23
    • 1970-01-01
    • 2011-02-28
    • 2012-02-20
    • 1970-01-01
    • 2011-07-06
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多