在外部函数中使用minidom appendChild()创建XML文件

时间:2015-10-12 11:22:31

标签: python xml minidom

为了使用Python创建XML文件,我在WriteXMLClass类中使用minidom。来自minidom的函数appendChild()经常会显得很安静,因此我想将它存储在外部函数中。但是,self.base的引用丢失了,我没有输出。

这应该是结果XML文件:

<ROOT>
       <CHILD1>
        </CHILD1>
       <CHILD2>
        </CHILD2>
</ROOT>

我到目前为止的代码:

import xml.dom.minidom as dom

    class WriteXMLClass(object):
        def __init__(self):
             self.base = dom.Document()

        def AddEmptyTag(self, tagname):
             tag = self.base.createElement(tagname)
             return tag    

        def CreateXML(self, Objects):
             self.base = dom.Document()

             tagdict = self.base.createElement('ROOT')
             self.base.appendChild(tagdict)

             tagCHILD1 = self.AddEmptyTag('CHILD1')
             tagdict.appendChild(tagCHILD1)
             tagCHILD2 = self.AddEmptyTag('CHILD2')
             tagdict.appendChild(tagCHILD2)

             self.base.writexml(PATH, "", "\t", "\r\n", "utf-8")

我如何在appendChild()中使用AddEmptyTag(),如下所示:??

import xml.dom.minidom as dom

    class WriteXMLClass(object):
        def __init__(self):
             self.base = dom.Document()

        def AddEmptyTag(self, tagname, PARENTNODE):   #NEW
             tag = self.base.createElement(tagname)
             PARENTNODE.appendChild(tag)              #NEW
             return tag    

        def CreateXML(self, Objects):
             self.base = dom.Document()

             tagdict = self.base.createElement('ROOT')
             self.base.appendChild(tagdict)

             tagCHILD = self.AddEmptyTag('CHILD1', tagdict) #NEW
             tagCHILD2 = self.AddEmptyTag('CHILD2', tagdict) #NEW

             self.base.writexml(PATH, "", "\t", "\r\n", "utf-8")

0 个答案:

没有答案