python - 我应该如何在 python 中解析这个 xml 字符串?

标签 python xml elementtree

我的 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图书馆。到目前为止,我已经尝试过 -

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 中一样,我们可以使用根访问它们 -

$xml = simplexml_load_string($data);
$status = $xml->SMSError;

最佳答案

您的文档上有命名空间,搜索时需要包含命名空间:

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() 方法也采用命名空间映射;您可以搜索任意前缀,并且会在该映射中查找该前缀,以节省输入:

nsmap = {'n': 'http://example.com'}
print root.find('n:Sent', namespaces=nsmap)
print root.find('n:MessageID', namespaces=nsmap)

关于python - 我应该如何在 python 中解析这个 xml 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14153988/

相关文章:

python - 如何将范围集合减少到最小范围集

java - 空指针异常 : fav_up_btn1 = null

java - 如何在 Spring Boot 中从端点响应中全局省略空 xml 标签?

python : How to add root node to an XML

python - 使用 python ElementTree 解析未知元素的 xml 文件

python - 类型错误 : unorderable types: dict() < dict()

python - 使用 dataclasses.MISSING 作为 Python 数据类的可选参数值?

python - Pandas:向前填充而不填充尾随 NaN

c# - LinqToXml 未按预期处理可空元素

python - 如何在 Python 中将多个 XML 节点复制到另一个文件