在python上迭代xml响应

2024-09-28 01:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个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>上的树时遇到问题,打印出的名称、查找标记或属性不适用于此结构。帮个小忙


Tags: namecomchildhttpwwwcountsomeot
1条回答
网友
1楼 · 发布于 2024-09-28 01:23:27

我认为使用接受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']

相关问题 更多 >

    热门问题