PyXB XML 对象到字符串
PyXB XML Object to String
给定一个 PyXB 对象,如何将其转换为字符串?
我使用 PyXB 生成了一个 XML 文档,然后我想使用 xmltodict
模块将其转换为字典。问题是 xmltodict.parse
采用类似字节的对象,而 PyXB 对象当然不是。
我在 python d1_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)
给定一个 PyXB 对象,如何将其转换为字符串?
我使用 PyXB 生成了一个 XML 文档,然后我想使用 xmltodict
模块将其转换为字典。问题是 xmltodict.parse
采用类似字节的对象,而 PyXB 对象当然不是。
我在 python d1_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)