2011-08-24 89 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'