【问题标题】:How to introduce new subelement node in an xml file using python如何使用python在xml文件中引入新的子元素节点
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 我应该更改“new_data = ET.SubElement(child_of_root, 'mimName');”符合“new_data = xml.etree.ElementTree.SubElement(child_of_root, 'mimName');” .我做了上面的一个,但是在 fun new_data = xml.etree.ElementTree.SubElement(child_of_root, 'mimName'); 中获得了文件“./test.py”,第 26 行。 AttributeError: 'str' object has no attribute 'etree' 错误。
  • 我的时间不多了。我可以告诉你的是,每当你使用 qoutes '' 时,类型都是字符串。但是,您正在某处作为代码中的标记。改变那个。确保您只在标签上使用ET,而不是简单的字符串。
猜你喜欢
  • 2022-12-13
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
相关资源
最近更新 更多