Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:使用lxml复制xml中的节点时标记不匹配_Python_Xml_Lxml_Python 3.7 - Fatal编程技术网

Python:使用lxml复制xml中的节点时标记不匹配

Python:使用lxml复制xml中的节点时标记不匹配,python,xml,lxml,python-3.7,Python,Xml,Lxml,Python 3.7,我是xml新手,正在尝试复制一个节点。虽然它复制了节点,但当我附加它时,结束标记不匹配。这是我正在解析的xml <doc> <branch name="release01" hash="f200013e"> <sub-branch name="subrelease01"> xml,sgml </sub-branch> </branch> </doc>

我是xml新手,正在尝试复制一个节点。虽然它复制了节点,但当我附加它时,结束标记不匹配。这是我正在解析的xml

<doc>
    <branch name="release01" hash="f200013e">
        <sub-branch name="subrelease01">
            xml,sgml
        </sub-branch>
    </branch>
</doc>

xml,sgml
下面是我用来解析xml的代码:

import lxml.etree as ET
import copy

tree = ET.ElementTree(file="doc2.xml")
root = tree.getroot()

lst_nodes = tree.findall("branch")
ele = 0

while ele < len(lst_nodes):
    ref = lst_nodes[ele]
    if (lst_nodes[ele].attrib.get("name") == "release01"):
        count = 0
        while count < 1:
            copied = copy.deepcopy(ref)
            ref.append(copied)
            count=count+1
    ele+=1

ET.dump(root)
将lxml.etree作为ET导入
导入副本
tree=ET.ElementTree(file=“doc2.xml”)
root=tree.getroot()
lst_nodes=tree.findall(“分支”)
ele=0
当ele
观察到的输出为:

<doc>
    <branch name="release01" hash="f200013e">
        <sub-branch name="subrelease01">
            xml,sgml
        </sub-branch>
    <branch name="release01" hash="f200013e">
        <sub-branch name="subrelease01">
            xml,sgml
        </sub-branch>
    </branch>
</branch>
</doc>

xml,sgml
xml,sgml

正如您所看到的,“分支”的结束标记不匹配。有人能帮我确定复制或附加节点时所犯的错误吗?

我相信您试图生成的输出是:

<doc>
    <branch name="release01" hash="f200013e">
        <sub-branch name="subrelease01">
            xml,sgml
        </sub-branch>
    </branch>
    <branch name="release01" hash="f200013e">
        <sub-branch name="subrelease01">
            xml,sgml
        </sub-branch>
    </branch>
</doc>

xml,sgml
xml,sgml
您所犯的错误是,您将
ref
的副本附加到构成
ref
自身的元素,而没有将副本放在
ref
之后(即,您希望副本是
ref
的兄弟,而不是子副本)。要实现所需的行为,您需要将ref的副本附加到
ref
的父元素,这可以通过使用
getparent()
方法,然后使用
append()
来实现,或者更方便地,您可以直接使用元素的
addnext()
方法

i、 e.将
ref.append(副本)
替换为
ref.addnext(副本)


谢谢你的回答。成功了。但是在第一个分支的结束标记之后,新的同级在同一行而不是新行中开始。漂亮的印花并没有解决问题。任何解决方案。这很奇怪,转储似乎只是为了根据API引用进行调试。打印tostring()方法的结果时是否会出现相同的问题?(使用pretty_print=True)以及何时将tostring()写入文件?是。我尝试使用tostring()方法写入文件。结果是一样的。无需在新同级的开头添加新行。根据此答案,使用移除空格的解析器实例化树对象。parser=ET.XMLParser(remove_blank_text=True)tree=ET.ElementTree(file=“doc2.xml”,parser=parser)lxml双注释中给出了此行为的解释: