使用python解析xml中具有特定匹配字符串的子标记

2024-06-25 06:08:15 发布

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

我想解析xml字符串,将标记topic作为父标记,Topic1,Topic2作为子标记。在

<?xml version="1.0" encoding="UTF-8"?><SignificantDevelopments Major="3" Minor="0" Revision="1" xmlns="urn:reuterscompanycontent:significantdevelopments03"><Topics><Topic1 Code="254">Regulatory / Company Investigation</Topic1><Topic2 Code="207">Mergers &amp; Acquisitions</Topic2><ParentTopic1 Code="6">Litigation / Regulatory</ParentTopic1><ParentTopic2 Code="4">Ownership / Control</ParentTopic2></Topics></SignificantDevelopments>

我只想解析这个xml,这样我就可以得到每个Topic标记的属性值,我只希望它在for循环中。在

我尝试使用以下代码:

^{pr2}$

我想在最后一行添加匹配的主题


Tags: 字符串标记topicversioncodexmlutfencoding
1条回答
网友
1楼 · 发布于 2024-06-25 06:08:15

例如,您可以检查tag属性是否以名称空间加上前缀Topic开头

from xml.etree import cElementTree as ET
root = ET.fromstring('<?xml version="1.0" encoding="UTF-8"?><SignificantDevelopments Major="3" Minor="0" Revision="1" xmlns="urn:reuterscompanycontent:significantdevelopments03"><Topics><Topic1 Code="254">Regulatory / Company Investigation</Topic1><Topic2 Code="207">Mergers &amp; Acquisitions</Topic2><ParentTopic1 Code="6">Litigation / Regulatory</ParentTopic1><ParentTopic2 Code="4">Ownership / Control</ParentTopic2></Topics></SignificantDevelopments>')
topics = [el for el in root.findall('*/*') if el.tag.startswith('{urn:reuterscompanycontent:significantdevelopments03}Topic')]
for topic in topics:
    print (topic.text)

或者更短

^{pr2}$

或者将检查放入if语句中的if语句中。在

相关问题 更多 >