使用 <!..> 访问 xml 元素属性

Access xml element attribute with <!..>

我想编写一个小程序来从 XML 文件中读取数据并将其写入 CSV。我通常使用元素树。

XML 文件起源于手机应用程序,看起来总是这样:

<waypoint><name><![CDATA[POI 2017-07-03 09:37:11nass]]></name> 
<coord lat="47.220430" lon="8.951071"/></waypoint>

访问坐标根及其内容(经度和纬度)没有任何问题。但是如何访问名字的信息:[CDATA[POI 2017-07-03 09:37:11nass]]

到目前为止,我的代码如下所示:

for poi in POIS:
    tree = etree.parse(rootwayp + poi)
    root = tree.getroot()
    for child in root:
        for childchild in child:
            print(childchild.tag, ':', childchild.attrib)

我想我需要为名称内容实现另一种读取方法,因为括号中不包含那里的信息。我曾尝试将信息作为 name 的子子项访问,但这不起作用(可能是因为括号中的 !?) ! 到底是什么?在 <!...> 是什么意思?

<![CDATA[...]]>是一个特殊的 marked section

您可以使用以下选择器来提取您需要的详细信息:

root = tree.getroot()

print(root.find('name').text)
print(root.find('coord').attrib.get('lat','n/a'))
print(root.find('coord').attrib.get('lon','n/a'))

# Output
POI 2017-07-03 09:37:11nass
47.220430
8.951071

使用 lxml,您可以提取整个 CDATA 部分,here is some doc about.