python to merge certain XML tags from file1 to file 2 -
i have 2 xmls. xml1 , xml2. update xml1 content of xml2.
xml1
<vdu xmlns="test:file"> <lsm> <m-id>v1</m-id> <name>v1</name> <communication>bi</communication> <states> <s-name>stage1</s-name> <state> <s-type>defaultstate</s-type> <s-func> <p-name>pkgname</p-name> <f-list> <f-name>funcname</f-name> <f-arg>{&}</f-arg> </f-list> </s-func> </state> <lib-path>libpath</lib-path> <e-list> <e-name>noevent</e-name> <event> <nss>inc</nss> <nfs>inc</nfs> <actions> <p-name>pkgname</p-name> <f-list> <f-name>tof</f-name> <f-arg></f-arg> </f-list> </actions> </event> </e-list>
xml2
<vdu xmlns="test:file"> <lsm> <m-id>v1</m-id> <name>v1</name> <communication>bi</communication> <e-list> <e-name>noevent</e-name> <event> <nss>inc</nss> <nfs>inc</nfs> <actions> <p-name>pkgname</p-name> <f-list> <f-name>tof</f-name> <f-arg></f-arg> </f-list> </actions> </event> </e-list>
i trying retrieve text xml2, , update each element in xml1 (i not sure how should though).this reached far before got stuck.
import xml.etree.elementtree et source = (r'c:\xml2.xml') destination = (r'c:\xml1.xml') source_tree = et.parse(source) source_root = source_tree.getroot() dest_tree = et.parse(destination) dest_root = dest_tree.getroot() xmltag = dest_root.tag newroot = et.element(xmltag) source_elem in source_root.iter('e-list'): ele_verbose in source_elem: newroot.append(source_elem) open_network in ele_verbose: newroot.append(open_network) et.elementtree(newroot).write(destination, xml_declaration=true, encoding='utf-8') # write copied elements in new file , not retain other tags in xml file.
if have better way achieve please suggest.
here's unprofessional way lxml (i don't have experience it):
from lxml import etree source = (r'test_xml2.xml') destination = (r'test_xml.xml') root1 = etree.parse(destination).getroot() root2 = etree.parse(source).getroot() all_elements1 = root1.findall('.//*') all_elements2 = root2.findall('.//*') def complete_tag_check(e1,e2): while e1.tag == e2.tag: if e1.tag == root1.tag: return true else: e1 = e1.getparent() e2 = e2.getparent() return false el2 in all_elements2: remove_el = false if el2.text not none , el2.text.strip()!='': el1 in all_elements1: ## # compare element tags ## if el1.tag == el2.tag: ## el1.text = el2.text ## remove_el = true ## break # compare tags in each step until # root. elements # same structure qualify. if complete_tag_check(el1,el2): el1.text = el2.text remove_el = true break # if have multiple tags same name in xmls, # last 1 xml2 replace in xml1. # avoid remove each element changed # text all_elements1 list. if remove_el: all_elements1.remove(el1) et = etree.elementtree(root1) et.write('test_xml3.xml', pretty_print=true) # wrote different file compare results
wiki
Comments
Post a Comment