Python中使用SAX生成XML输出时如何插入DTD DOCTYPE内容
我正在尝试使用 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
感谢您的帮助。
I am trying to generate a large XML file using python(actually jython) xml.sax.saxutils.XMLGenerator.
I would like to include DTD information but I could not figure out how to pass the DTD string to SAX. Here is the sample SAX writer class:
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
Appreciate your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以子类化
XMLGenerator
并添加write()
方法。下面是一个示例:out.xml 中的结果输出:
You could subclass
XMLGenerator
and add awrite()
method. Here is an example:Resulting output in out.xml: