【发布时间】:2017-12-06 07:03:31
【问题描述】:
我是 Python 编程新手。 我有一个 xml 文件,其中一个 sn-p 如下。
<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);
【问题讨论】:
-
有人可以帮忙吗?
-
如果你使用 Python 2.6,为什么问题会被标记为“python-3.x”和“python-2.7”?
标签: python xml python-3.x python-2.7 elementtree