My XML string is -

xmlData = """

false

00000000-0000-0000-0000-000000000000

false

NoError

false

0001-01-01T00:00:00

"""

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

Although, I am able to print the tags with -

for child in root:

print child.tag

//child.tag for the tag Cancelled is - {http://example.com}Cancelled

and their respective values with -

for child in root:

print child.text

How do I get something like -

print child.Queued // will print false

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')

output:

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)

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐