Extracting specific xml tag value using python

依然范特西╮ 提交于 2020-01-23 02:47:06

问题


I have XML data which looks like this:

    <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>

I want to extract the tag value text2 from the tag k='search'>value>text.

In my code, I am trying the following:

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

This gives me both text1 and text2 as output. Out of these I need only text2. I could handle this in my program to have an if statement to filter only the text2 value, but I want to find a more robust way to do this in findall().

I have tried this code instead to specifically extract only text2 as output.

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

But this gives me an error -

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 ([)

What should I change to get only text2 as my output?


回答1:


Thank you har07 and tdelaney . I had an old version of elementtree as you mentioned . After pointing to a newer version of python the code is working fine now .




回答2:


You can extract text from tag, using below example

import xml.etree.ElementTree as ET

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


来源:https://stackoverflow.com/questions/35662542/extracting-specific-xml-tag-value-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!