使用 python ElementTree 解析 xml 文件中的未知元素
我希望从一个多用途 xml 文件中提取所有标签名称及其相应的数据。然后将该信息保存到 python 字典中(例如,标签 = 键,数据 = 值)。问题是标签名称和值未知且数量未知。
<some_root_name>
<tag_x>bubbles</tag_x>
<tag_y>car</tag_y>
<tag...>42</tag...>
</some_root_name>
我正在使用 ElementTree,可以成功提取根标签,并可以通过引用标签名称来提取值,但无法找到一种方法来简单地迭代标签和数据而不引用标签名称。
任何帮助都会很棒。
谢谢。
I wish to extract all the tag names and their corresponding data from a multi-purpose xml file. Then save that information into a python dictionary (e.g tag = key, data = value). The catch being the tags names and values are unknown and of unknown quantity.
<some_root_name>
<tag_x>bubbles</tag_x>
<tag_y>car</tag_y>
<tag...>42</tag...>
</some_root_name>
I'm using ElementTree and can successfully extract the root tag and can extract values by referencing the tag names, but haven't been able to find a way to simply iterate over the tags and data without referencing a tag name.
Any help would be great.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:
从文件而不是字符串中读取
EDIT:
To read from file instead of from string
如果您确实想要
42
而不是'42'
,则需要更加努力且不太优雅地工作。If you really want
42
instead of'42'
, you'll need to work a little harder and less elegantly.您可以使用 xml.sax.handler 解析 XML:
产生
You could use xml.sax.handler to parse the XML:
yields
这可以在 python 中使用 lxml 来完成
This could be done using lxml in python