【问题标题】:extracting value from xml node从 xml 节点中提取值
【发布时间】:2015-12-30 05:53:36
【问题描述】:

我知道从以下格式的 xml 中获取值:

<note>
    <col1>Tove</col1>
    <col2>J</col2>
    <test2>
        <a> a </a>
        <b> b </b>
        <c> c </c>
        <d> d </d>
    </test2>
    <code
        a="1"
        b="2"
        c="3"
    />
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

我提取的值如下:

for a in xmls.getiterator():
    b = a.find("col1") # or col2
    if b is not None:
        print b.text  #this helps in extracting the value
        break

我的问题是我需要在test2code 节点中提取值,但是使用上述方法,我得到的输出为None

预期输出

理想情况如下,但最好获取像 a,b,c,d,1,2,3 这样的直接节点值

            <a> a </a>
            <b> b </b>
            <c> c </c>
            <d> d </d>

           and

            a="1"
            b="2"
            c="3"

如果我们有目标节点名称,从 xml 中提取不同类型值的本地方法是什么?

相关:

【问题讨论】:

    标签: python xml python-2.7 xml-parsing


    【解决方案1】:

    我会使用lxml.etree.xpath().attrib 来获取属性值:

    import lxml.etree as ET
    
    data = """<note>
        <col1>Tove</col1>
        <col2>J</col2>
        <test2>
            <a> a </a>
            <b> b </b>
            <c> c </c>
            <d> d </d>
        </test2>
        <code
            a="1"
            b="2"
            c="3"
        />
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
    </note>
    """
    
    tree = ET.fromstring(data)
    
    for note in tree.xpath("//note"):
        test2_values = [value.strip() for value in note.xpath(".//test2/*/text()")]
        code_attrs = note.find("code").attrib
    
        print(test2_values)
        print(code_attrs)
    

    在这里,我们基本上是遍历所有note节点(假设有多个),获取内部test2节点下所有节点的文本以及code节点具有的所有属性。

    打印:

    ['a', 'b', 'c', 'd']
    {'b': '2', 'c': '3', 'a': '1'}
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2020-05-05
    • 2015-05-23
    相关资源
    最近更新 更多