我在xml响应中有这个结构
<reponse xmls="http://www.some.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.some.com/ot ot.xsd ">
<OneTree> </OneTree>
<TwoTree>
<count>10</count>
<alist>
<aelement>
<Name>FirstEntry</Name>
</aelement>
<aelement>
<Name>FirstEntry</Name>
</aelement>
</alist>
</TwoTree>
我试图打印名字上的值
到目前为止,我已设法打印<count>
tree = ElementTree.fromstring(response.content)
for child in tree:
if (child.tag == '{http://www.some.com/ot}TwoTree'):
print child[0].text
我在<alist>
上获取树时遇到问题并打印出名称,查找标签或attrib对此结构不起作用。帮助不大?
答案 0 :(得分:0)
我认为使用接受basic XPath syntax的findall()
方法会更容易:
namespaces = {'d': 'http://www.some.com'}
result = tree.findall('.//d:Name', namespaces)
print [r.text for r in result]
raw = '''<response xmlns="http://www.some.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.some.com/ot ot.xsd ">
<OneTree> </OneTree>
<TwoTree>
<count>10</count>
<alist>
<aelement>
<Name>FirstEntry</Name>
</aelement>
<aelement>
<Name>FirstEntry</Name>
</aelement>
</alist>
</TwoTree>
</response>'''
from xml.etree import ElementTree as ET
tree = ET.fromstring(raw)
namespaces = {'d': 'http://www.some.com'}
result = tree.findall('.//d:Name', namespaces)
print [r.text for r in result]
输出
['FirstEntry', 'FirstEntry']