PyXB XML对象到字符串

2024-04-24 23:41:17 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个PyXB对象,如何将其转换为字符串?在

我使用PyXB生成一个XML文档,然后使用xmltodict模块将其转换为字典。问题是xmltodict.parse使用一个类似字节的对象,而PyXB对象则不是。在


Tags: 模块对象字符串文档字典字节parsexml
1条回答
网友
1楼 · 发布于 2024-04-24 23:41:17

我在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))
    )

例如,可以使用

serialize_gen(pyxb_object, utf-8)

要将对象转换为字符串,它将被称为

serialize_gen(pyxb_object, None)

相关问题 更多 >