代码之家  ›  专栏  ›  技术社区  ›  bux

如何获取lxml元素的字符串转储

  •  0
  • bux  · 技术社区  · 7 年前

    我有LXML Element 对象:

    >>> from lxml import etree
    >>> xml_str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<state type=\"before_battle\">\n</state>"
    >>> etree.fromstring(xml_str.encode('utf-8'))
    <Element state at 0x7fd04b957e48>
    

    如何获取字符串转储 元素 是吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   nosklo    7 年前

    首先将元素对象存储在变量中

    >>> d = etree.fromstring(xml_str.encode('utf-8'))
    

    然后使用 tostring 函数来自 lxml.etree 模块:

    >>> etree.tostring(d)
    '<state type="before_battle">\n</state>'
    

    对于其他用例,您可以查看 lxml.etree Tutorial .