给定一个PyXB对象,如何将其转换为字符串?
我使用PyXB生成一个XML文档,然后使用xmltodict模块将其转换为字典。问题是xmltodict.parse接受一个类似字节的对象,而PyXB对象当然不是。
发布于 2018-04-19 01:03:51
我在python python库中找到了一个方法来实现这一点。该方法接受一个PyXB对象,并使用给定的编码对其进行序列化。
def serialize_gen(obj_pyxb, encoding, pretty=False, strip_prolog=False):
"""Serialize a PyXB object to XML
- If {pretty} is True, format for human readability.
- If {strip_prolog} is True, remove any XML prolog (e.g., <?xml version="1.0"
encoding="utf-8"?>), from the resulting string.
"""
assert is_pyxb(obj_pyxb)
assert encoding in (None, 'utf-8')
try:
if pretty:
pretty_xml = obj_pyxb.toDOM().toprettyxml(indent=' ', encoding=encoding)
# Remove empty lines in the result caused by a bug in toprettyxml()
if encoding is None:
pretty_xml = re.sub(r'^\s*$\n', r'', pretty_xml, flags=re.MULTILINE)
else:
pretty_xml = re.sub(b'^\s*$\n', b'', pretty_xml, flags=re.MULTILINE)
else:
pretty_xml = obj_pyxb.toxml(encoding)
if strip_prolog:
if encoding is None:
pretty_xml = re.sub(r'^<\?(.*)\?>', r'', pretty_xml)
else:
pretty_xml = re.sub(b'^<\?(.*)\?>', b'', pretty_xml)
return pretty_xml.strip()
except pyxb.ValidationError as e:
raise ValueError(
'Unable to serialize PyXB to XML. error="{}"'.format(e.details())
)
except pyxb.PyXBException as e:
raise ValueError(
'Unable to serialize PyXB to XML. error="{}"'.format(str(e))
)例如,可以将PyXB对象解析为UTF-8
serialize_gen(pyxb_object, utf-8)
要将对象转换为字符串,它将被调用为
serialize_gen(pyxb_object, None)
https://stackoverflow.com/questions/49867521
复制相似问题