Python XML add element to file -
i have 1000 xml files, , missing element. made script search through xml's , print element. wanted add ability add element if isnt there, unsuccessful.
as can see below, dvt3 isnt there , needs added.
my code
xmlparser = etree.xmlparser(remove_blank_text=true) f in os.listdir(directory): if f.endswith(".xml"): xmlfile = directory + '/' + f tree = etree.parse(xmlfile, parser=xmlparser) root = tree.getroot() hardwarerevisionnode = root.find(".//hardwarerevision") try: print f + ' : ' + hardwarerevisionnode.text except exception e: print str(e) print xmlfile #wearable = root.find(".//wearable") childnode = etree.element(".//wearable") childnode.text = "dvt2" childnode.append(childnode) tree.write(xmlfile, pretty_print=true)
xml file
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <speech> <results> <breakpoint name="asr_start_recognition" elapsedtime="00:00:00.000" /> </results> <meta> <dialog> <sessionuuid>7c9b1e3a-b22f-4793-818f-72bc6e7b84a9</sessionuuid> </dialog> <asr> <engine> <name>rockhopper</name> <version>1.0.0.61</version> </engine> <wrapper> <name>rockhopperasrengine</name> <version>1.8.2</version> </wrapper> <wrapper> <name>core</name> <version>1.8.2</version> </wrapper> <resource> <name>language model</name> <version>1.4.4</version> </resource> </asr> <application> <name>fightclub</name> <version>0.1.550</version> <commit>8f7a411</commit> <builddate>2016-03-09t18:16z</builddate> <branch>head</branch> </application> <wearable> <firmware>1.0.183 - fcb1app000-1611w0183</firmware> </wearable> </meta> </speech>
xml file want
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <speech> <results> <breakpoint name="asr_start_recognition" elapsedtime="00:00:00.000" /> </results> <meta> <dialog> <sessionuuid>7c9b1e3a-b22f-4793-818f-72bc6e7b84a9</sessionuuid> </dialog> <asr> <engine> <name>rockhopper</name> <version>1.0.0.61</version> </engine> <wrapper> <name>rockhopperasrengine</name> <version>1.8.2</version> </wrapper> <wrapper> <name>core</name> <version>1.8.2</version> </wrapper> <resource> <name>language model</name> <version>1.4.4</version> </resource> </asr> <application> <name>fightclub</name> <version>0.1.550</version> <commit>8f7a411</commit> <builddate>2016-03-09t18:16z</builddate> <branch>head</branch> </application> <wearable> <firmware>1.0.183 - fcb1app000-1611w0183</firmware> <hardwarerevision>dvt3</hardwarerevision> </wearable> </meta> </speech>
you can try out xmltodict.
import xmltodict x open(myfile) f: xmldictionary=x.parse(f.read(),'utf-8') xmldictionary['speech']['meta']['wearable'].update({"hardwarerevision": "dvt3"}) output = x.unparse(xmldictionary) open(outfile,'w') out: out.write(output)
make run in parallel if want, , if storage concern replace contents of files (or delete old ones immediatelly after new ones made).
Comments
Post a Comment