【问题标题】:Preserving XML comments and processing instructions that occur before the root element保留在根元素之前出现的 XML 注释和处理指令
【发布时间】:2017-12-26 16:20:57
【问题描述】:

我需要添加一个新标签并写回一个 XML。这是我的 XML 文件。

<?xml version="1.0" encoding="UTF-8"?>
    <!--Arbortext, Inc., 1988-2011, v.4002-->
    <!DOCTYPE reference-configuration-statement PUBLIC "-//Juniper Networks//DTD Jbook Software Guide//EN"
     "file:////cmsxml/IWServer/default/main/TechPubsWorkInProgress/STAGING/bin/dtds/jbook-sw/jbook-sw.dtd">
    <?Pub UDT _nopagebreak _touchup KeepsKeep="yes" KeepsPrev="no" KeepsNext="no" KeepsBoundary="page"?>
    <?Pub UDT _bookmark _target?>
    <?Pub UDT instructions _comment FontColor="red"?>
    <?Pub UDT instructions-DUPLICATE1 _comment FontColor="red"?>
    <?Pub UDT __target_1 _target?>
    <?Pub UDT __target_3 _target?>
    <?Pub UDT __target_2 _target?>
    <?Pub UDT _bookmark-DUPLICATE1 _target?>
    <?Pub UDT __target_4 _target?>
    <?Pub EntList copy trade micro reg plusmn deg middot mdash ndash nbsp
    caret cent check acute frac12 frac13 frac14 frac15 frac16 frac18 frac23
    frac25 frac34 frac35 frac38 frac45 frac56 frac58 frac78 ohm pi sup sup1
    sup2 sup3 rsquo?>
    <?Pub Inc?>
    <root topic-id="25775"

我能够用 etree 完成任务。

path="C:/Users/pshahul/Desktop/Official/Automation/Write_XMl_files/Source/"
            add=(path, Filename)
            myfile=s.join(add)
            try:
                et = xml.etree.ElementTree.parse(myfile)
                tree=etree.parse(myfile)
                docinfo=tree.docinfo.encoding
                root=et.getroot()
                elem = root.find('cli-help')
                if elem is None:
                    new_tag=ET.Element("cli-help")
                    new_tag.text=final
                    root.insert(2,new_tag)
                    et.write(myfile,encoding=docinfo, xml_declaration=True)
                else:
                    elem.text=final
                    et.write(myfile,encoding=docinfo, xml_declaration=True)
            except OSError:
                pass
        else:
            raise TypeError
    except TypeError:
        continue

现在,我得到了 DOCTYPE 和 XML 声明,但以下内容被跳过。

<!--Arbortext, Inc., 1988-2011, v.4002-->
     <?Pub UDT _nopagebreak _touchup KeepsKeep="yes" KeepsPrev="no" KeepsNext="no" KeepsBoundary="page"?>
    <?Pub UDT _bookmark _target?>
    <?Pub UDT instructions _comment FontColor="red"?>
    <?Pub UDT instructions-DUPLICATE1 _comment FontColor="red"?>
    <?Pub UDT __target_1 _target?>
    <?Pub UDT __target_3 _target?>
    <?Pub UDT __target_2 _target?>
    <?Pub UDT _bookmark-DUPLICATE1 _target?>
    <?Pub UDT __target_4 _target?>
    <?Pub EntList copy trade micro reg plusmn deg middot mdash ndash nbsp
    caret cent check acute frac12 frac13 frac14 frac15 frac16 frac18 frac23
    frac25 frac34 frac35 frac38 frac45 frac56 frac58 frac78 ohm pi sup sup1
    sup2 sup3 rsquo?>
    <?Pub Inc?>

我如何保存它?我需要这些行回到我的 XML 文件中。加上cmets。我发现 cmets 也不见了。

【问题讨论】:

  • 您只发布了部分代码和错误。查看[SO]: How to ask[SO]: mcve 了解更多询问相关详情。您的第一个 sn-p 中的缩进是错误的(最后一个 else)。此外,缩进代码时使用 4 个 SPACE,而不是 TAB
  • 完全不清楚你想要什么。请提供minimal reproducible example
  • 我已经把我的整个代码放在这里了。我的问题是 1. 如何保存 DOCTYPE 2. 如何更改 lt;和GT;到
  • 问题还是不太清楚。当我们要求minimal reproducible example 时,我们并不是要求您提供整个代码。我们要求重现问题的最小代码段。你应该删除所有不需要的东西。
  • 其实我是个白痴。使用 lxml 但使用 ET 编写。我使用了 lxml,它保留了所有内容。一个美容错误花了我几个小时。抱歉,感谢您的回答。

标签: python xml-parsing comments lxml processing-instruction


【解决方案1】:

根据OP的建议,这里的(或a)解决方案是使用lxml,如下所示,它将保留cmets以及处理指令:

import lxml.etree as ET
tree = ET.parse(filename)

【讨论】:

    【解决方案2】:

    documentation of ElementTree 明确表示这是不可能的:

    注意:并非 XML 输入的所有元素最终都会成为解析树的元素。目前,该模块跳过输入中的任何 XML cmets、处理指令和文档类型声明

    对我来说开箱即用的方法是 minidom。除非文档非常大,否则可以将其保存在内存中

    from xml.dom import minidom
    from xml.dom import Node
    
    xml_string = "<?xml version='1.0'?><!--comment--><root><!--inside comment--><child/></root>"
    xml_doc = minidom.parseString(xml_string)
    for node in xml_doc.getchildNodes:
        if node.nodeType == Node.COMMENT_NODE:
            print("Comment", node.data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-05
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      相关资源
      最近更新 更多