繁体   English   中英

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM