Python XML迭代

Python XML迭代,python,xml-parsing,Python,Xml Parsing,我试图从请求-响应中遍历XML。现在,我的python代码如下所示: data = requests.post(url, data=xml, headers=headers).content tree = ElementTree.fromstring(data) 我的XML如下所示: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http:/

我试图从请求-响应中遍历XML。现在,我的python代码如下所示:

data = requests.post(url, data=xml, headers=headers).content
tree = ElementTree.fromstring(data)
我的XML如下所示:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetPasswordResponse xmlns="https://tempuri.org/">
    <GetPasswordResult>
    <Content>ThisisContent</Content>
    <UserName>ExampleName</UserName>
    <Address>ExServer</Address>
    <Database>tempdb</Database>
    <PolicyID>ExPolicy</PolicyID>
    <Properties>
        <KeyAndValue>
            <key>Content</key>
            <value>ThisisContent</value>
        </KeyAndValue>
        <KeyAndValue>
            <key>ReconcileIsWinAccount</key>
            <value>Yes</value>
        </KeyAndValue>
    </Properties>
    </GetPasswordResult>
</GetPasswordResponse>
</soap:Body></soap:Envelope>'

这是内容
示例名称
ExServer
tempdb
展览
内容
这是内容
对账账户
对
'

如何使用ElementTree提取、和标记的值?我尝试了许多不同的方法,但似乎无法获得任何可访问的值。

这有点棘手,因为元素有名称空间,但没有前缀

从xml.etree导入ElementTree作为ET
数据=“”\
这是内容
示例名称
ExServer
tempdb
展览
内容
这是内容
对账账户
对
'''
tree=ET.fromstring(数据)
nmsp={
“肥皂”:http://schemas.xmlsoap.org/soap/envelope/',
“x”:”https://tempuri.org/',
}#名称空间前缀分配
打印(tree.find('.//x:Content',namespace=nmsp).text)
打印(tree.find('.//x:UserName',namespace=nmsp).text)
打印(tree.find('.//x:PolicyID',namespace=nmsp).text)

>P>有一个不需要考虑XML命名空间的库。

from simplified_scrapy import utils, SimplifiedDoc, req
xml = '''
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetPasswordResponse xmlns="https://tempuri.org/">
    <GetPasswordResult>
    <Content>ThisisContent</Content>
    <UserName>ExampleName</UserName>
    <Address>ExServer</Address>
    <Database>tempdb</Database>
    <PolicyID>ExPolicy</PolicyID>
    <Properties>
        <KeyAndValue>
            <key>Content</key>
            <value>ThisisContent</value>
        </KeyAndValue>
        <KeyAndValue>
            <key>ReconcileIsWinAccount</key>
            <value>Yes</value>
        </KeyAndValue>
    </Properties>
    </GetPasswordResult>
</GetPasswordResponse>
</soap:Body></soap:Envelope>
'''

# xml = req.post(url, data=xml, headers=headers)
doc = SimplifiedDoc(xml)
nodes = doc.select('GetPasswordResult').selects('Content|UserName|PolicyID')
print ([(node.tag, node.text) for node in nodes])

张贴你认为是你最好的尝试,我们可以与之合作。此XML使用名称空间,这在ElementTree中有点棘手。这是一个很好的资源。
[('Content', 'ThisisContent'), ('UserName', 'ExampleName'), ('PolicyID', 'ExPolicy')]