我有多个xml文件,布局非常相似。
在下面的示例中,我对xml树1,对象1进行了一些更改,我想将这些更改复制到xml树2和3:
示例XMLS:
<example_data>
<object class="example" id="xml_tree_1">
<object class="multi_object" id="object_1">
<style many_attributes="stuff_and_changes"/>
<object class="object_1" id="random_12">
<style many_attributes="things"/>
</object>
<object class="object_2" id="random_21">
<style many_attributes="things"/>
</object>
</object>
<object class="object_1" id="object_2">
<style many_attributes="stuff"/>
</object>
</object>
</example_data>
<example_data>
<object class="example" id="xml_tree_2">
<object class="multi_object" id="object_1">
<style many_attributes="stuff"/>
<object class="object_1" id="random_23">
<style many_attributes="stuff"/>
</object>
<object class="object_2" id="random_32">
<style many_attributes="stuff"/>
</object>
</object>
<object class="object_1" id="object_2">
<style many_attributes="stuff"/>
</object>
</object>
</example_data>
<example_data>
<object class="example" id="xml_tree_3">
<object class="multi_object" id="object_1">
<style many_attributes="stuff"/>
<object class="object_1" id="random_45">
<style many_attributes="stuff"/>
</object>
<object class="object_2" id="random_54">
<style many_attributes="stuff"/>
</object>
</object>
<object class="object_1" id="object_2">
<style many_attributes="stuff"/>
</object>
</object>
</example_data>
在对一棵树进行了一些更改后,如何将这些更改复制到其他树?
我不知道如何开始。
示例PYTHON:
import os
import xml.etree.ElementTree as et
all_trees = {}
def main():
generate_trees("path_to_xmls")
copy_style_attributes_to_all_trees("object_1", "xml_tree_1")
write_trees()
def copy_style_attributes_to_all_trees(object_id, source):
for key in all_trees:
tree = all_trees[key]
for dest in tree.iter("object"):
if (dest.get("id") == object_id):
# copy object 1 (and inner objects) style from source to dest object
# I have no idea how to do this
def generate_trees(directory):
for root, dirs, files in os.walk(directory):
for f in files:
if f.endswith(".xml"):
fpath = os.path.join(root, f)
tree = et.parse(fpath)
all_trees[fpath] = tree
def get_tree(filename):
for key in all_trees:
if (key.find(filename) != -1):
return all_trees[key]
return None
def write_trees():
for fpath in all_trees:
all_trees[fpath].write(fpath)
if __name__ == '__main__':
main()
应该怎么做?