2011-08-24 119 views
2

我遇到了lxml的一个小问题。我正在将XML文档转换为HTML文档。 原始XML看起来是这样的(它看起来像HTML,但它在XML文档):Python lxml更改标签层次结构?

<p>Localization - Eiffel tower? Paris or Vegas <p>Bayes theorem p(A|B)</p></p> 

当我做这个(产品上面的字符串)

lxml.html.tostring(lxml.html.fromstring(item)) 

我得到这样的:

<div><p>Localization - Eiffel tower? Paris or Vegas </p><p>Bayes theorem p(A|B)</p></div> 

我没有与<DIV>小号任何问题,但事实是,“贝叶斯定理”的段落不再嵌套外款所列这是一个问题。

任何人都知道为什么lxml正在这样做以及如何阻止它?谢谢。

回答

12

LXML是这样做的,因为它没有存储无效的HTML和<p>元素can't be nested在HTML:

P元素表示一个段落。它不能包含块级元素(包括P本身)。

+0

+1这就是答案! – SingleNegationElimination

+0

呵呵。这是我不知道的。谢谢! –

1

您正在使用lxml的HTML解析器,而不是XML解析器。试试这个:

>>> from lxml import etree 
>>> item = '<p>Eiffel tower? Paris or Vegas <p>Bayes theorem p(A|B)</p></p>' 
>>> root = etree.fromstring(item) 
>>> etree.tostring(root, pretty_print=True) 
'<p>Eiffel tower? Paris or Vegas <p>Bayes theorem p(A|B)</p></p>\n'