迭代python上的xml响应

时间:2016-03-09 02:43:06

标签: python xml

我在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对此结构不起作用。帮助不大?

1 个答案:

答案 0 :(得分:0)

我认为使用接受basic XPath syntaxfindall()方法会更容易:

namespaces = {'d': 'http://www.some.com'}
result = tree.findall('.//d:Name', namespaces)
print [r.text for r in result]

complete demo

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