[英]Keep lxml from creating self-closing tags
我有一個(舊)工具,它不理解像<STATUS/>
這樣的自閉合標簽。 因此,我們需要使用這樣的打開/關閉標簽來序列化我們的 XML 文件: <STATUS></STATUS>
。
目前我有:
>>> from lxml import etree
>>> para = """<ERROR>The status is <STATUS></STATUS>.</ERROR>"""
>>> tree = etree.XML(para)
>>> etree.tostring(tree)
'<ERROR>The status is <STATUS/>.</ERROR>'
如何使用打開/關閉的標簽進行序列化?
<ERROR>The status is <STATUS></STATUS>.</ERROR>
解決方案
>>> from lxml import etree
>>> para = """<ERROR>The status is <STATUS></STATUS>.</ERROR>"""
>>> tree = etree.XML(para)
>>> for status_elem in tree.xpath("//STATUS[string() = '']"):
... status_elem.text = ""
>>> etree.tostring(tree)
'<ERROR>The status is <STATUS></STATUS>.</ERROR>'
似乎<STATUS>
標簽被分配了None
的text
屬性:
>>> tree[0]
<Element STATUS at 0x11708d4d0>
>>> tree[0].text
>>> tree[0].text is None
True
如果您將<STATUS>
標簽的text
屬性設置為空字符串,您應該得到您要查找的內容:
>>> tree[0].text = ''
>>> etree.tostring(tree)
'<ERROR>The status is <STATUS></STATUS>.</ERROR>'
考慮到這一點,您可能可以在寫出 XML 之前遍歷 DOM 樹並修復text
屬性。 像這樣的東西:
# prevent creation of self-closing tags
for node in tree.iter():
if node.text is None:
node.text = ''
如果你 tostring lxml dom is HTML
,你可以使用
etree.tostring(html_dom, method='html')
防止像<a />
這樣的自閉合標簽
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.