我的 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>"""
我正在尝试解析并获取标签的值 - Cancelled、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
不过,我可以打印标签 -
for child in root:
print child.tag
//child.tag for the tag Cancelled is - {http://example.com}Cancelled
及其各自的值 -
for child in root:
print child.text
我如何获得类似 -
print child.Queued // will print false
就像在 PHP 中一样,我们可以使用根访问它们 -
$xml = simplexml_load_string($data);
$status = $xml->SMSError;
最佳答案
您的文档上有命名空间,搜索时需要包含命名空间:
root = ET.fromstring(xmlData)
print root.find('{http://example.com}Sent',)
print root.find('{http://example.com}MessageID')
输出:
<Element '{http://example.com}Sent' at 0x1043e0690>
<Element '{http://example.com}MessageID' at 0x1043e0350>
find()
和findall()
方法也采用命名空间映射;您可以搜索任意前缀,并且会在该映射中查找该前缀,以节省输入:
nsmap = {'n': 'http://example.com'}
print root.find('n:Sent', namespaces=nsmap)
print root.find('n:MessageID', namespaces=nsmap)
关于python - 我应该如何在 python 中解析这个 xml 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14153988/