首页 > 解决方案 > 为什么在以下 xml 文件中有额外的标签附加以及如何删除它们?

问题描述

我编写了以下函数来编写 xml 文件

def dict_to_xml1(tag, d):
    elem = ET.Element(tag)
    for key,val in mydic.items():
        child = ET.Element("token")
        child.text = str(key)
        elem.append(child)
    #     print(key, val)
        child1 = ET.Element("provenance")
        for i in val:
            child2 = ET.SubElement(child1,"from")
            child2.text = str(i[0])
            child3 = ET.SubElement(child1,"where")
            child3.text = str(i[1])
        elem.append(child2)
        elem.append(child3)
        elem.append(child1)
            
    #         print(key,i)
    return elem

mydic 是一个形式的字典(给出一个小样本):

{'java': [['yarn-site.xml', 'configuration.value'],
  ['yarn-site.xml', 'configuration.value']],
 'home': [['yarn-site.xml', 'configuration.value'],
  ['mapred-site.xml', 'configuration.value'],
  ['mapred-site.xml', 'configuration.value'],
  ['yarn-site.xml', 'configuration.value'],
 'hadoop': [['yarn-site.xml', 'configuration.value'],
  ['yarn-site.xml', 'configuration.value'],
  ['capacity-scheduler.xml', 'configuration.value'],
  ['kms-acls.xml', 'configuration.name'],
  ['kms-acls.xml', 'configuration.name']}

我正在运行函数 dict_to_xml1 的示例输出是:

    <index>
      <token>java</token>
      <from>yarn-site.xml</from>
      <where>configuration.value</where>
      <provenance>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
      </provenance>
      <token>home</token>
      <from>yarn-site.xml</from>
      <where>configuration.value</where>
      <provenance>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>mapred-site.xml</from>
        <where>configuration.value</where>
        <from>mapred-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
        <from>yarn-site.xml</from>
        <where>configuration.value</where>
      </provenance>
</index>

我试图了解为什么每个标签之前都有标签<from>以及我应该如何删除它。提到的标签只应该出现在标签内。<where><provenance><provenance>

有人可以指出我在 dict_to_xml1 函数中做错了什么吗?

标签: pythonxml

解决方案


推荐阅读