How should I parse this xml string in python?

梦想的初衷 提交于 2019-12-12 08:01:27

问题


My XML string is -

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>"""

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;

回答1:


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:

<Element '{http://example.com}Sent' at 0x1043e0690>
<Element '{http://example.com}MessageID' at 0x1043e0350>

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)



回答2:


If you're set on Python standard XML libraries, you could use something like this:

root = ET.fromstring(xmlData)
namespace = 'http://example.com'

def query(tree, nodename):
    return tree.find('{{{ex}}}{nodename}'.format(ex=namespace, nodename=nodename))

queued = query(root, 'Queued')
print queued.text



回答3:


You can create a dictionary and directly get values out of it...

tree = ET.fromstring(xmlData)

root = {}

for child in tree:
    root[child.tag.split("}")[1]] = child.text

print root["Queued"]



回答4:


With lxml.etree:

In [8]: import lxml.etree as et

In [9]: doc=et.fromstring(xmlData)

In [10]: ns={'n':'http://example.com'}

In [11]: doc.xpath('n:Queued/text()',namespaces=ns)
Out[11]: ['false']

With elementtree you can do:

import xml.etree.ElementTree as ET    
root=ET.fromstring(xmlData)    
ns={'n':'http://example.com'}
root.find('n:Queued',namespaces=ns).text
Out[13]: 'false'


来源:https://stackoverflow.com/questions/14153988/how-should-i-parse-this-xml-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!