kusogaki
kusogaki

Reputation: 47

Python 3.5 Can't write xml using via minidom

I'm a newb with python and xml parsing, so I've spent a good amount of time (over 20 hours) rummaging through forums to find how to achieve what I'm after. Most of the threads I've seen had solutions for my problem, but they are dated and the python version is different so I can't use them; they didn't work when I tried.

What I want to do:

What I'm using:

Here is the error I'm getting when trying to write out the new xml:

this_xml.write(ofile)
AttributeError: 'Document' object has no attribute 'write'

I've tried ElementTree and lxml, but I've made the most progress with minidom so I would prefer to use it.

Here (I think) is the pertinent code:

import tkinter
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from 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 the #do stuff part I'm reading certain node data, changing it, and printing the result. The prints are looking good, but now I just can't get those changes to take form.

Before I revert back to python 2.7 (on which most of the walkthroughs/tutorials/examples I've seen are based) I would greatly appreciate any help.

Upvotes: 4

Views: 9490

Answers (1)

Ben
Ben

Reputation: 1701

You're getting this error because this_xml is a Document, and Document objects don't have a write() method. Take a look at the documentation. xml.dom.minidom.parse() returns a Document, which is a subclass of Node. You'll probably want to use one of the methods listed here to write the XML to a file -- either toxml() or toprettyxml() to turn the Document into a string that you can write to a file, or writexml() to write the XML directly:

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

Note also that you shouldn't use a capitalized camelcase name like OutputFileName for a regular variable. That name format is reserved for class names. The idiomatic way to write this variable name in Python would be output_file_name.

Upvotes: 5

Related Questions