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?
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 .
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.