如何用python顺序读取xml中的多个元素

2024-03-29 01:47:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个xml文件,格式如下:

<stage rend="italic center" type="entrance"> aaaaa </stage>
<sp who="#F-mm-duk">bbbbb </sp>
<sp who="#smdwo">ccccc </sp>
<sp who="#F-mm-acb">cccc </sp>
<stage rend="italic center" type="entrance"> ddddd </stage>

如何从这些元素中提取文本以便: aaaaa级 bbbbb的 ccccc公司 滴滴涕


Tags: 文件格式typexmlstagespmmcenter
1条回答
网友
1楼 · 发布于 2024-03-29 01:47:53

如果你不关心一些特殊情况,比如文本包含'>', '</'

可以使用一个正则表达式来提取所有节点的文本。你知道吗

代码如下:

import re

xml_str = """
<stage rend="italic center" type="entrance"> aaaaa </stage>
<sp who="#F-mm-duk">bbbbb </sp>
<sp who="#smdwo">ccccc </sp>
<sp who="#F-mm-acb">cccc </sp>
<stage rend="italic center" type="entrance"> ddddd </stage>
"""

match_list = re.findall(r'>(?P<xml>.*)</', xml_str, flags=0)
print (match_list)

输出:

[' aaaaa ', 'bbbbb ', 'ccccc ', 'cccc ', ' ddddd ']
[Finished in 0.287s]

但是更好的解决方案是使用一个类似xml.etree.elementtree的XML库,然后为节点挑选所有文本。你知道吗

代码如下:

import xml.etree.ElementTree as ET

xml_str = """
<?xml version="1.0"?>
<data>
<stage rend="italic center" type="entrance"> aaaaa </stage>
<sp who="#F-mm-duk">bbbbb </sp>
<sp who="#smdwo">ccccc </sp>
<sp who="#F-mm-acb">cccc </sp>
<stage rend="italic center" type="entrance"> ddddd </stage>
</data>
"""

tree = ET.fromstring(xml_str.strip())
for child in tree:
    print(child.text)

一些XML库支持XPath(xml.etree.elementtree提供了有限的支持)。您可以在google上搜索它,然后研究如何用XPath实现相同的输出。你知道吗

相关问题 更多 >