我应该如何在python中解析此xml字符串? [英] How should I parse this xml string in python?
问题描述
我的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 库。到目前为止,我已经尝试过-
I am trying to parse and get the values of tags - Cancelled, MessageId, SMSError, etc. I am using python's Elementtree library. So far, I have tried things like -
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
我怎么得到类似的东西-
How do I get something like -
print child.Queued // will print false
就像PHP一样,我们可以用根访问它们-
Like in PHP we can access them with the root -
$xml = simplexml_load_string($data);
$status = $xml->SMSError;
推荐答案
您的文档上有一个名称空间,您需要在搜索时包括名称空间:
Your document has a namespace on it, you need to include the namespace when searching:
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()
方法也带有名称空间映射;您可以搜索任意前缀,然后在该地图中查找该前缀,以节省输入内容:
The find()
and findall()
methods also take a namespace map; you can search for a arbitrary prefix, and the prefix will be looked up in that map, to save typing:
nsmap = {'n': 'http://example.com'}
print root.find('n:Sent', namespaces=nsmap)
print root.find('n:MessageID', namespaces=nsmap)
这篇关于我应该如何在python中解析此xml字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!