本文整理汇总了Python中xml.sax.saxutils.XMLGenerator方法的典型用法代码示例。如果您正苦于以下问题:Python saxutils.XMLGenerator方法的具体用法?Python saxutils.XMLGenerator怎么用?Python saxutils.XMLGenerator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.sax.saxutils
的用法示例。
在下文中一共展示了saxutils.XMLGenerator方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _out_tag
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def _out_tag(self, name, attrs, isLeaf):
# sorted attributes -- don't want attributes output in random order, which is what the XMLGenerator class does
self.output.write(" " * self.indent)
self.output.write("<%s" % name)
sortedNames = sorted( attrs.keys() ) # sorted list of attribute names
for name in sortedNames:
value = attrs[ name ]
# if not of type string,
if not isinstance(value, str):
# turn it into a string
value = str(value)
self.output.write(" %s=%s" % (name, quoteattr(value)))
if isLeaf:
self.output.write("/")
else:
self.indent += 4
self.output.write(">\n")
示例2: unparse
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def unparse(input_dict, output=None, encoding='utf-8', full_document=True,
short_empty_elements=False,
**kwargs):
"""Emit an XML document for the given `input_dict` (reverse of `parse`).
The resulting XML document is returned as a string, but if `output` (a
file-like object) is specified, it is written there instead.
Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted
as XML node attributes, whereas keys equal to `cdata_key`
(default=`'#text'`) are treated as character data.
The `pretty` parameter (default=`False`) enables pretty-printing. In this
mode, lines are terminated with `'\n'` and indented with `'\t'`, but this
can be customized with the `newl` and `indent` parameters.
"""
if full_document and len(input_dict) != 1:
raise ValueError('Document must have exactly one root.')
must_return = False
if output is None:
output = StringIO()
must_return = True
if short_empty_elements:
content_handler = XMLGenerator(output, encoding, True)
else:
content_handler = XMLGenerator(output, encoding)
if full_document:
content_handler.startDocument()
for key, value in input_dict.items():
_emit(key, value, content_handler, full_document=full_document,
**kwargs)
if full_document:
content_handler.endDocument()
if must_return:
value = output.getvalue()
try: # pragma no cover
value = value.decode(encoding)
except AttributeError: # pragma no cover
pass
return value
示例3: publish
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def publish(self, handler):
""" This method produces the XML representation of the object to be included in the feed. In your implementation,
make sure you always call this base class method before adding your own code.
Keyword arguments:
handler -- An xml.sax.saxutils.XMLGenerator instance that you can use to create the XML representation of the object.
"""
self.handler = handler
示例4: rss
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def rss(self):
output = StringIO()
handler = saxutils.XMLGenerator(output, 'UTF-8')
handler.startDocument()
handler.startElement("rss", self._get_attributes())
self.publish(handler)
handler.endElement("rss")
handler.endDocument()
return output.getvalue()
示例5: __init__
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def __init__(self, file, **kwargs):
self.item_element = kwargs.pop('item_element', 'item')
self.root_element = kwargs.pop('root_element', 'items')
self._configure(kwargs)
if not self.encoding:
self.encoding = 'utf-8'
self.xg = XMLGenerator(file, encoding=self.encoding)
示例6: unparse
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def unparse(input_dict, output=None, encoding='utf-8', **kwargs):
"""Emit an XML document for the given `input_dict` (reverse of `parse`).
The resulting XML document is returned as a string, but if `output` (a
file-like object) is specified, it is written there instead.
Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted
as XML node attributes, whereas keys equal to `cdata_key`
(default=`'#text'`) are treated as character data.
The `pretty` parameter (default=`False`) enables pretty-printing. In this
mode, lines are terminated with `'\n'` and indented with `'\t'`, but this
can be customized with the `newl` and `indent` parameters.
"""
((key, value),) = input_dict.items()
must_return = False
if output is None:
output = StringIO()
must_return = True
content_handler = XMLGenerator(output, encoding)
content_handler.startDocument()
_emit(key, value, content_handler, **kwargs)
content_handler.endDocument()
if must_return:
value = output.getvalue()
try: # pragma no cover
value = value.decode(encoding)
except AttributeError: # pragma no cover
pass
return value
示例7: filter_rdf
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def filter_rdf (input, output):
"""filter_rdf(input:file, output:file)
Parses the XML input from the input stream, filtering out all
elements and attributes that are in the RDF namespace.
"""
output_gen = saxutils.XMLGenerator(output)
parser = sax.make_parser()
filter = RDFFilter(parser)
filter.setFeature(handler.feature_namespaces, True)
filter.setContentHandler(output_gen)
filter.setErrorHandler(handler.ErrorHandler())
filter.parse(input)
示例8: serialize
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def serialize(self, data):
"""
Serializes data to XML so that it can be
sent to backend, if data is not a dictionary
raises a SerializationException
Params:
`data`: A dictionary containing the data to serialize
Return:
`xml`: Returns a string containing data serialized to XML
"""
if not isinstance(data, dict):
raise SerializationException("Can't serialize data, must be a dictionary.")
stream = StringIO()
self.generator = XMLGenerator(stream, "utf-8")
self.generator.startDocument()
self.generator.startElement("request", {})
self._parse(data)
self.generator.endElement("request")
self.generator.endDocument()
return stream.getvalue()
示例9: unparse
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def unparse(input_dict, output=None, encoding='utf-8', full_document=True,
short_empty_elements=False,
**kwargs):
"""Emit an XML document for the given `input_dict` (reverse of `parse`).
The resulting XML document is returned as a string, but if `output` (a
file-like object) is specified, it is written there instead.
Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted
as XML node attributes, whereas keys equal to `cdata_key`
(default=`'#text'`) are treated as character data.
The `pretty` parameter (default=`False`) enables pretty-printing. In this
mode, lines are terminated with `'\n'` and indented with `'\t'`, but this
can be customized with the `newl` and `indent` parameters.
"""
if full_document and len(input_dict) != 1:
raise ValueError('Document must have exactly one root.')
must_return = False
if output is None:
output = StringIO()
must_return = True
if short_empty_elements:
content_handler = XMLGenerator(output, encoding, True)
else:
content_handler = XMLGenerator(output, encoding)
if full_document:
content_handler.startDocument()
for key, value in input_dict.items():
_emit(key, value, content_handler, full_document=full_document,
**kwargs)
if full_document:
content_handler.endDocument()
if must_return:
value = output.getvalue()
try: # pragma no cover
value = value.decode(encoding)
except AttributeError: # pragma no cover
pass
return value
示例10: unparse
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def unparse(input_dict, output=None, encoding='utf-8', full_document=True,
**kwargs):
"""Emit an XML document for the given `input_dict` (reverse of `parse`).
The resulting XML document is returned as a string, but if `output` (a
file-like object) is specified, it is written there instead.
Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted
as XML node attributes, whereas keys equal to `cdata_key`
(default=`'#text'`) are treated as character data.
The `pretty` parameter (default=`False`) enables pretty-printing. In this
mode, lines are terminated with `'\n'` and indented with `'\t'`, but this
can be customized with the `newl` and `indent` parameters.
"""
if full_document and len(input_dict) != 1:
raise ValueError('Document must have exactly one root.')
must_return = False
if output is None:
output = StringIO()
must_return = True
content_handler = XMLGenerator(output, encoding)
if full_document:
content_handler.startDocument()
for key, value in input_dict.items():
_emit(key, value, content_handler, full_document=full_document,
**kwargs)
if full_document:
content_handler.endDocument()
if must_return:
value = output.getvalue()
try: # pragma no cover
value = value.decode(encoding)
except AttributeError: # pragma no cover
pass
return value
示例11: write_xml
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def write_xml(self, outfile, encoding="iso-8859-1"):
from xml.sax import saxutils
handler = saxutils.XMLGenerator(outfile, encoding)
handler.startDocument()
self.publish(handler)
handler.endDocument()
示例12: save
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def save(self, filename=None):
if self.filename and filename is None:
filename = self.filename
if len(self.__dict__) == 0 or filename is None:
return
try:
fileobj = get_fileptr(filename, True)
except Exception as e:
LOG.error('Cannot write preferences into %s %s', filename, e)
return
writer = XMLGenerator(out=fileobj, encoding=self.system_encoding)
writer.startDocument()
defaults = XmlConfigParser.__dict__
items = self.__dict__.items()
items.sort()
writer.startElement('preferences', {})
writer.characters('\n')
for key, value in items:
if key in defaults and defaults[key] == value:
continue
if key in ['filename', 'app']:
continue
writer.characters('\t')
writer.startElement('%s' % key, {})
str_value = path_unicode(value.__str__())
if isinstance(value, str):
str_value = "'%s'" % (escape_quote(str_value))
writer.characters(str_value)
writer.endElement('%s' % key)
writer.characters('\n')
writer.endElement('preferences')
writer.endDocument()
fileobj.close()
示例13: __init__
# 需要导入模块: from xml.sax import saxutils [as 别名]
# 或者: from xml.sax.saxutils import XMLGenerator [as 别名]
def __init__(self, file, **kwargs):
"""
:param file: the file-like object to use for exporting the data.
It's write method should accept bytes (a disk file opened in
binary mode, a io.BytesIO object, etc)
:param kwargs: root_element (str) – The name of root element in
the exported XML.
:param kwargs: item_element (str) – The name of each item element
in the exported XML.
A typical output of this exporter would be:
<?xml version="1.0" encoding="utf-8"?>
<items>
<item>
<name>Color TV</name>
<price>1200</price>
</item>
<item>
<name>DVD player</name>
<price>200</price>
</item>
</items>
Unless overridden in the serialize_field() method, multi-valued
fields are exported by serializing each value inside a <value>
element. This is for convenience, as multi-valued fields are
very common.
For example, the item:
>>> Item(name=['John', 'Doe'], age='23')
Would be serialized as:
<?xml version="1.0" encoding="utf-8"?>
<items>
<item>
<name>
<value>John</value>
<value>Doe</value>
</name>
<age>23</age>
</item>
</items>
"""
super().__init__()
self.item_element = kwargs.pop('item_element', 'item')
self.root_element = kwargs.pop('root_element', 'items')
self._configure(kwargs)
if not self.encoding:
self.encoding = 'utf-8'
self.xg = XMLGenerator(file, encoding=self.encoding)