Python 找到 xml 中的主要元素

Python find the main element in the xml

问题很简单。我需要使用 python.

在 xml 中找到主要元素的标签
<CATALOG>
    <PLANT>
        <COMMON>Bloodroot</COMMON>
        <BOTANICAL>Sanguinaria canadensis</BOTANICAL>
        <ZONE>4</ZONE>
        <LIGHT>Mostly Shady</LIGHT>
        <PRICE>.44</PRICE>
        <AVAILABILITY>031599</AVAILABILITY>
    </PLANT>
    <PLANT>
        <COMMON>Columbine</COMMON>
        <BOTANICAL>Aquilegia canadensis</BOTANICAL>
        <ZONE>3</ZONE>
        <LIGHT>Mostly Shady</LIGHT>
        <PRICE>.37</PRICE>
        <AVAILABILITY>030699</AVAILABILITY>
    </PLANT>
    <PLANT>
        <COMMON>Marsh Marigold</COMMON>
        <BOTANICAL>Caltha palustris</BOTANICAL>
        <ZONE>4</ZONE>
        <LIGHT>Mostly Sunny</LIGHT>
        <PRICE>.81</PRICE>
        <AVAILABILITY>051799</AVAILABILITY>
    </PLANT>
</CATALOG>

它应该return“PLANT”。保证主元素只有一个

<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>

这应该return“书”。

从现在开始感谢。祝你有美好的一天!

终于找到解决办法了。我递归地迭代每个元素并计算每个元素的子元素。在循环结束时,具有最多子元素的元素成为主要元素。这是代码:

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)