【发布时间】:2020-06-17 09:04:00
【问题描述】:
我是 xml 新手,正在尝试复制一个节点。虽然它复制了节点,但当我附加它时,结束标签不匹配。这是我正在解析的 xml。
<doc>
<branch name="release01" hash="f200013e">
<sub-branch name="subrelease01">
xml,sgml
</sub-branch>
</branch>
</doc>
这是我用来解析 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)
观察到的输出是:
<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>
如您所见,“分支”的结束标记不匹配。有人可以帮我找出我在复制或附加节点时犯的错误吗?
【问题讨论】:
标签: python xml lxml python-3.7