我的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