PyXB XML对象到字符串

时间:2018-04-16 23:10:12

标签: python xml pyxb

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

我使用PyXB生成XML文档,然后我想使用(Invoke-RestMethod -Uri https://Adminmanagement.3171r06a.azcatcpec.com/metadata/endpoints?api-version=1.0).authentication 模块将其转换为字典。问题是xmltodict采用类似字节的对象,PyXB对象当然不是。

1 个答案:

答案 0 :(得分:0)

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