【问题标题】:Adding a comment to existing XML File using Python 3使用 Python 3 向现有 XML 文件添加注释
【发布时间】:2018-03-05 10:50:41
【问题描述】:

我有以下 XML 文件:

<xml_connection_file xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xsi:noNamespaceSchemaLocation="mcf.xsd">
  <version> 1.0.0 </version>
  <connection_group>
    <id> 1 </id>
    <connected_to>
      <part>
        <base> A </base>
      </part>
      <part>
        <base> B </base>
      </part>
    </connected_to>
  </connection_group>
</xml_connection_file>

我希望在主节点(xml_connection_file)中添加注释。我在 python3 中编写了以下代码,但出现错误说'lxml.etree._ElementTree' 没有属性'insert'

from lxml import etree
from ansa import utils

my_selected_file = utils.SelectOpenFile(0, 'xml files (*.mcf)')

tree = etree.parse(my_selected_file[0])

comment = etree.Comment('my comments')
tree.insert(1,comment)

tree.write('new_file.mcf')

谁能告诉我我做错了什么?提前感谢!

【问题讨论】:

    标签: python xml python-3.x xml-parsing python-3.4


    【解决方案1】:
    from lxml import etree
    from ansa import utils
    
    my_selected_file = utils.SelectOpenFile(0, 'xml files (*.xml)')
    
    tree = etree.parse(my_selected_file[0])
    mainnode = tree.getroot()
    comm = etree.Comment('--the filename--')
    mainnode.insert(1, comm)
    tree.write('output.xml')
    

    我之前没有提取xml文件的Element,并在tree中应用了insert。现在,我使用getroot() 提取了Element(主节点),并在Element 中使用insert 插入了评论

    【讨论】:

    • 请不要留下仅代码的答案,请在您的答案中添加解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2022-06-23
    • 2018-04-23
    相关资源
    最近更新 更多