【问题标题】:How to insert DTD DOCTYPE content when using SAX to generate XML output in Python在 Python 中使用 SAX 生成 XML 输出时如何插入 DTD DOCTYPE 内容
【发布时间】:2011-06-19 03:55:22
【问题描述】:

我正在尝试使用 python(实际上是 jython)xml.sax.saxutils.XMLGenerator 生成一个大型 XML 文件。 我想包含 DTD 信息,但我不知道如何将 DTD 字符串传递给 SAX。这是示例 SAX 编写器类:

from xml.sax.saxutils import XMLGenerator

class xml_writer:
    def __init__(self, output, encoding):
        """
        an XML writer object that generate xml output to a file
        """
        xmlwriter = XMLGenerator(output, encoding)
        xmlwriter.startDocument()
        self._writer = xmlwriter
        self._output = output
        self._encoding = encoding

        self.attr_vals = {}
        self.attr_qnames = {}
        return

    def start_elem(self, name):
        name = unicode(name)
        attrs = AttributesNSImpl(self.attr_vals, self.attr_qnames)
        self._writer.startElementNS((None, name), name, attrs)
        self._writer._out.write('\n')
        self.attr_qnames = {}
        self.attr_vals = {}

    def end_elem(self, name):
        name = unicode(name)
        self._writer.endElementNS((None, name), name)
        self._writer._out.write('\n')

    def setAttribute(self, aname, value):
        aname = unicode(aname)
        value = unicode(value)
        self.attr_vals[(None, aname)] = value
        self.attr_qnames[(None, aname)] = aname

    def close(self):
        """
        Clean up 
        """
        self._writer.endDocument()
        return

感谢您的帮助。

【问题讨论】:

    标签: python xml jython dtd


    【解决方案1】:

    您可以继承 XMLGenerator 并添加一个 write() 方法。这是一个例子:

    import sys
    from xml.sax.saxutils import XMLGenerator
    
    class MyXMLGenerator(XMLGenerator):
        def __init__(self, out=sys.stdout, encoding="UTF-8"):
            XMLGenerator.__init__(self, out, encoding)
            self.out = out
    
        def write (self,s):
            self.out.write(s)
    
    def writexml(out):
        xmlwriter = MyXMLGenerator(out)
        xmlwriter.startDocument()
        xmlwriter.write("<!DOCTYPE test SYSTEM 'test.dtd'>\n")
        xmlwriter.startElement('test', {"a": "1"})
        xmlwriter.characters('abc123')
        xmlwriter.endElement('test')
        xmlwriter.endDocument()
    
    if __name__ == '__main__':
        writexml(out=open("out.xml", "w"))
    

    out.xml 中的结果输出:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE test SYSTEM 'test.dtd'>
    <test a="1">abc123</test>
    

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 2015-04-19
      • 2011-01-25
      • 2010-12-26
      • 1970-01-01
      • 2017-08-19
      相关资源
      最近更新 更多