如何解决Python查找xml中的主要元素
问题很简单。我需要使用python在xml中找到主要元素的标签。
<CATALOG>
<PLANT>
<COMMON>Bloodroot</COMMON>
<BOTANICAL>Sanguinaria canadensis</BOTANICAL>
<ZONE>4</ZONE>
<LIGHT>Mostly Shady</LIGHT>
<PRICE>$2.44</PRICE>
<AVAILABILITY>031599</AVAILABILITY>
</PLANT>
<PLANT>
<COMMON>Columbine</COMMON>
<BOTANICAL>Aquilegia canadensis</BOTANICAL>
<ZONE>3</ZONE>
<LIGHT>Mostly Shady</LIGHT>
<PRICE>$9.37</PRICE>
<AVAILABILITY>030699</AVAILABILITY>
</PLANT>
<PLANT>
<COMMON>Marsh Marigold</COMMON>
<BOTANICAL>Caltha palustris</BOTANICAL>
<ZONE>4</ZONE>
<LIGHT>Mostly Sunny</LIGHT>
<PRICE>$6.81</PRICE>
<AVAILABILITY>051799</AVAILABILITY>
</PLANT>
</CATALOG>
它应该返回“植物”。保证只有一个主元素。
<catalog>
<book id="bk101">
<author>Gambardella,Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls,Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,an evil sorceress,and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets,Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England,the young survivors lay the
foundation for a new society.</description>
</book>
</catalog>
这应该返回“书”。
从现在开始谢谢。祝你有美好的一天!
解决方法
终于找到了解决办法。我递归地迭代每个元素并计算每个元素的子元素。在循环结束时,具有最多子元素的元素成为主元素。代码如下:
node_name = ""
xmlTree = ET.parse(temp_file)
frequencies = dict()
root = xmlTree.getroot()
def findCount(root) -> dict():
if len(list(root)) > 0:
for child in list(root):
tag = child.tag
ns_index = tag.find('}')
if ns_index >= 0:
tag = child.tag[ns_index + 1:]
if len(list(child)) > 0:
frequencies[tag] = len(list(root))
findCount(child)
findCount(root)
maxCount = 0
maxName = ""
for key,value in frequencies.items():
if value > maxCount:
maxName = key
maxCount = value
print(maxName)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。