【发布时间】:2014-02-06 00:31:53
【问题描述】:
请记住,我对 Python 很陌生。如果 sample2.xml 中不存在,我正在尝试将几个 XML 节点从 sample1.xml 复制到 out.xml。
这是我卡住之前的距离
import xml.etree.ElementTree as ET
tree = ET.ElementTree(file='sample1.xml')
addtree = ET.ElementTree(file='sample2.xml')
root = tree.getroot()
addroot = addtree.getroot()
for adel in addroot.findall('.//cars/car'):
for el in root.findall('cars/car'):
with open('out.xml', 'w+') as f:
f.write("BEFORE\n")
f.write(el.tag)
f.write("\n")
f.write(adel.tag)
f.write("\n")
f.write("\n")
f.write("AFTER\n")
el = adel
f.write(el.tag)
f.write("\n")
f.write(adel.tag)
我不知道我错过了什么,但它只是复制了实际的“tag”本身。
输出如下:
BEFORE
car
car
AFTER
car
car
所以我缺少子节点,还有<、>、</、> 标签。预期结果如下。
sample1.xml:
<cars>
<car>
<use-car>0</use-car>
<use-gas>0</use-gas>
<car-name />
<car-key />
<car-location>hawaii</car-location>
<car-port>5</car-port>
</car>
</cars>
sample2.xml:
<cars>
<old>
1
</old>
<new>
8
</new>
<car />
</cars>
out.xml 中的预期结果(最终产品)
<cars>
<old>
1
</old>
<new>
8
</old>
<car>
<use-car>0</use-car>
<use-gas>0</use-gas>
<car-name />
<car-key />
<car-location>hawaii</car-location>
<car-port>5</car-port>
</car>
</cars>
所有其他节点 old 和 new 必须保持不变。我只是想用它的所有子节点和孙子节点(如果存在)替换 <car />。
【问题讨论】:
标签: python xml xpath elementtree