3

我有以 XML 文件形式出现的数据。我还获得了一个 XSLT 来将 XML 转换为 HTML。我可以使用 lxml 执行转换,但是,我想在转换后更改一些 HTML 标记。如何将这个新的 etree 转换为 HtmlElements,以便我可以专门使用某些方法,如 .cssselect() 等。

4

1 回答 1

1
>>> import lxml.etree
>>> import lxml.html
>>>
>>> xmlstring = '''\
... <?xml version='1.0' encoding='ASCII'?>
... <root><a class="here">link1</a><a class="there">link2</a></root>
... '''
>>> root = lxml.etree.fromstring(xmlstring)
>>> root.cssselect('a.here')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'lxml.etree._Element' object has no attribute 'cssselect'

lxml.etree.tostring(root)->lxml.html.fromstring(..)

>>> root = lxml.html.fromstring(lxml.etree.tostring(root))
>>> root.cssselect('a.here')
[<Element a at 0x2989308>]

获取 XML 输出:

>>> print lxml.etree.tostring(root, xml_declaration=True)
<?xml version='1.0' encoding='ASCII'?>
<root><a class="here">link1</a><a class="there">link2</a></root>
于 2013-06-21T17:09:37.510 回答