Python:使用lxml复制xml中的节点时标记不匹配
我是xml新手,正在尝试复制一个节点。虽然它复制了节点,但当我附加它时,结束标记不匹配。这是我正在解析的xmlPython:使用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>
<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双注释中给出了此行为的解释: