如何使用python在xml文件中引入新的子元素节点

2024-10-03 15:22:49 发布

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

我是Python编程新手。 我有一个xml文件,其中一个片段如下所示。你知道吗

<relationship name="a_to_b">
  <containment>
    <parent>
      <hasClass name="a" />
    </parent>
    <child>
      <hasClass name="b" />
    </child>
  </containment>
</relationship>

现在我要用下面的内容更新这个部分。你知道吗

<relationship name="a_to_b">
  <containment>
    <parent>
      <hasClass name="a">
         <mimName>top</mimName>
       </hasClass>
    </parent>
    <child>
      <hasClass name="b">
        <mimName>top</mimName>
      </hasClass>
    </child>
  </containment>
</relationship>

我正在使用ElmentTree模块。 我怎样才能做到这一点。 Python 2.6版。你知道吗

我正在使用下面的代码。你知道吗

tree = ET.ElementTree(file=xml) ;
root=tree.getroot() ;
print("Root tag of xml : "+root.tag) ;
#child_of_root=root;
#print("Root tag attribute of xml : "+root.attrib) ;



def fun(root):
   #if root.tag is not 'relationship':
      for child_of_root in root :
          #print("Tag : "+child_of_root.tag) ;
          attribut=child_of_root.attrib ;
          #print "Value : %s" %  attribut.get('name')
          if (child_of_root.tag == 'hasClass' and attribut.get('name') == 'MeContext') or (child_of_root.tag == 'hasClass' and attribut.get('name') == 'ManagedElement') :
           print(child_of_root.tag,attribut.get('name')) ;
           new_data = ET.SubElement(child_of_root, 'mimName');
           new_data.text = 'Top' 
       fun(child_of_root) 

fun(root);

Tags: ofnamechildgettagrootxmlparent
1条回答
网友
1楼 · 发布于 2024-10-03 15:22:49

使用xml.etree.ElementTree.SubElement在另一个标记中添加标记。复制自Python.org网站-&燃气轮机

>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>

相关问题 更多 >