Hus*_*ain 7 python xml elementtree
我的XML字符串是 -
xmlData = """<SMSResponse xmlns="http://example.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Cancelled>false</Cancelled>
<MessageID>00000000-0000-0000-0000-000000000000</MessageID>
<Queued>false</Queued>
<SMSError>NoError</SMSError>
<SMSIncomingMessages i:nil="true"/>
<Sent>false</Sent>
<SentDateTime>0001-01-01T00:00:00</SentDateTime>
</SMSResponse>"""
Run Code Online (Sandbox Code Playgroud)
我试图解析并获取标签的值 - Canceled,MessageId,SMSError等.我正在使用python的Elementtree库.到目前为止,我尝试过像 -
root = ET.fromstring(xmlData)
print root.find('Sent') // gives None
for child in root:
print chil.find('MessageId') // also gives None
Run Code Online (Sandbox Code Playgroud)
虽然,我能够用 - 打印标签 -
for child in root:
print child.tag
//child.tag for the tag Cancelled is - {http://example.com}Cancelled
Run Code Online (Sandbox Code Playgroud)
和他们各自的价值 -
for child in root:
print child.text
Run Code Online (Sandbox Code Playgroud)
我如何获得类似的东西 -
print child.Queued // will print false
Run Code Online (Sandbox Code Playgroud)
就像在PHP中一样,我们可以使用root访问它们 -
$xml = simplexml_load_string($data);
$status = $xml->SMSError;
Run Code Online (Sandbox Code Playgroud)
您的文档上有一个命名空间,您需要在搜索时包含命名空间:
root = ET.fromstring(xmlData)
print root.find('{http://example.com}Sent',)
print root.find('{http://example.com}MessageID')
Run Code Online (Sandbox Code Playgroud)
输出:
<Element '{http://example.com}Sent' at 0x1043e0690>
<Element '{http://example.com}MessageID' at 0x1043e0350>
Run Code Online (Sandbox Code Playgroud)
该find()和findall()方法也需要一个命名空间的地图; 您可以搜索任意前缀,并在该地图中查找前缀,以节省输入:
nsmap = {'n': 'http://example.com'}
print root.find('n:Sent', namespaces=nsmap)
print root.find('n:MessageID', namespaces=nsmap)
Run Code Online (Sandbox Code Playgroud)