繁体   English   中英

使用python提取特定的xml标签值

[英]Extracting specific xml tag value using python

我有如下所示的 XML 数据:

    <root>
      <results preview='0'>
        <meta>
          <fieldOrder>
        <field>title</field>
        <field>search</field>
          </fieldOrder>
        </meta>
        <messages>
          <msg type="DEBUG">msg1</msg>
          <msg type="DEBUG">msg2</msg>
        </messages>
        <result offset='0'>
          <field k='title'>
        <value>
          <text>text1</text>
        </value>
          </field>
          <field k='search'>
        <value>
          <text>text2</text>
        </value>
          </field>
        </result>
      </results>
    </root>

我想从标签k='search'>value>text提取标签值text2

在我的代码中,我正在尝试以下操作:

for atype in root.findall(".//text"):
    print(atype.text)

这给了我text1text2作为输出。 其中我只需要text2 我可以在我的程序中处理这个问题,让if语句只过滤text2值,但我想在findall()找到一种更强大的方法来做到这一点。

我已经尝试使用此代码专门仅提取text2作为输出。

for atype in root.findall(".//field[@k='search']//text"):
    print(atype.text)

但这给了我一个错误 -

File "command_curl", line 49, in <module>
for atype in root.findall(".//field[@k='search']//text"):
File "/usr/lib64/python2.6/xml/etree/ElementTree.py", line 355, in findall
return ElementPath.findall(self, path)
File "/usr/lib64/python2.6/xml/etree/ElementPath.py", line 198, in findall
return _compile(path).findall(element)
File "/usr/lib64/python2.6/xml/etree/ElementPath.py", line 176, in _compile
p = Path(path)
File "/usr/lib64/python2.6/xml/etree/ElementPath.py", line 93, in __init__
"expected path separator (%s)" % (op or tag)
SyntaxError: expected path separator ([)

我应该改变什么才能只得到text2作为我的输出?

谢谢 har07 和 tdelaney。 正如你提到的,我有一个旧版本的 elementtree。 在指向更新版本的 python 之后,代码现在工作正常。

您可以使用以下示例从标签中提取文本

import xml.etree.ElementTree as ET

tree = ET.parse("sample.xml")
root = tree.getroot()
for tags in root.findall(".//text"):
    print(tags.text)

暂无
暂无

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

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