Python 3.5 Can't write xml using via minidom -


i'm newb python , xml parsing, i've spent amount of time (over 20 hours) rummaging through forums find how achieve i'm after. of threads i've seen had solutions problem, dated , python version different can't use them; didn't work when tried.

what want do:

  • parse xml
  • alter contents based on conditions
  • rewrite out entire xml changes new xml formatting retained

what i'm using:

  • python 3.5
  • minidom , tkinter modules

here error i'm getting when trying write out new xml:

this_xml.write(ofile)
attributeerror: 'document' object has no attribute 'write'

i've tried elementtree , lxml, i've made progress minidom prefer use it.

here (i think) pertinent code:

import tkinter tkinter import * tkinter import messagebox tkinter import filedialog xml.dom.minidom import parse import xml import os import xml.dom.minidom  root = tk() root.withdraw() file_path = filedialog.askopenfilename(filetypes=[("xml",".xml")]) filename, file_extension = os.path.splitext(os.path.basename(file_path))  if file_extension ==".xml":     outputfilename = filename[:-2] + "vs_" + filename[-2:] + "_new" + file_extension     this_xml = xml.dom.minidom.parse(file_path)     xml_contents = this_xml.documentelement      #do stuff      ofile = open(outputfilename, 'wb')     this_xml.write(ofile)       #xml_contents.write(ofile) 

i'm sure there're tons of stupid calls i'm doing here. in #do stuff part i'm reading node data, changing it, , printing result. prints looking good, can't changes take form.

before revert python 2.7 (on of walkthroughs/tutorials/examples i've seen based) appreciate help.

you're getting error because this_xml document, , document objects don't have write() method. take @ documentation. xml.dom.minidom.parse() returns document, subclass of node. you'll want use 1 of methods listed here write xml file -- either toxml() or toprettyxml() turn document string can write file, or writexml() write xml directly:

with open("myfile.xml", "w") xml_file:     this_xml.writexml(xml_file) 

note shouldn't use capitalized camelcase name outputfilename regular variable. name format reserved class names. idiomatic way write variable name in python output_file_name.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -