我的XML字符串 -我该如何解析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>"""
我试图解析并获得标签的值 - 已取消,的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中,我们可以用root访问它们 -
$xml = simplexml_load_string($data);
$status = $xml->SMSError;
所以基本上我每次要访问标签文本时都必须指定“{http://example.com}”? – Hussain
@HussainTamboli:'find'和'findall'也有一个'namespaces = mapping'参数,但是当有一个默认名称空间时,这似乎没有用处。 'lxml'处理这一切好得多。 –
查看@ eclaird的回答。我想你也是这样做的。+1 – Hussain