android - How to copy element from one xml to another xml with python -
i have 2 xmls (they happen android text resources), first 1 is:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="txt_t1">aaaa</string> </resources>
and second is
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="txt_t2">bbbb</string> </resources>
i know attribute of element want copy, in example it's txt_t1. using python, how copy other xml , paste right behind txt_t2?
lxml king of xml parsing. i'm not sure if looking for, try this
from lxml import etree et # select parser , make remove whitespace # discard xml file formatting parser = et.xmlparser(remove_blank_text=true) # element tree of both of files src_tree = et.parse('src.xml', parser) dest_tree = et.parse('dest.xml', parser) # root element "resources" # want add new element dest_root = dest_tree.getroot() # anywhere in source document find "string" tag # has "name" attribute value of "txt_t1" src_tag = src_tree.find('//string[@name="txt_t1"]') # append tag dest_root.append(src_tag) # overwrite xml file et.elementtree(dest_root).write('dest.xml', pretty_print=true, encoding='utf-8', xml_declaration=true)
this assumes, first file called src.xml , second dest.xml. assumes element under need copy new element parent element. if not, can use find method find parent need or if don't know parent, search tag 'txt_t2' , use tag.getparent() parent.
Comments
Post a Comment