在 XML 属性中添加空白 space,在 Python 中使用 lxml
Adding a blank space in an XML attrib with lxml in Python
from lxml import etree
html = etree.Element("html")
body = etree.SubElement(html, "body")
body.text = "TEXT"
body.set("p style", "color:red")
print(etree.tostring(html))
给我错误:ValueError:无效的属性名称 u'p style'
您不能在 XML 中包含带有 space 的属性,这就是 lxml
和 etree
的用途。 XML 规范说明什么是有效的属性名称 here.
如果您正在努力实现这一目标:
<html><body p style="color:red">TEXT</body></html>
您不能在 XML 中这样做。您可以在 HTML 中做类似的事情:空属性。有关详细信息,请参阅 the HTML5 specification。但是您不会使用上面编写的那种代码来获得该结果。
如果您试图获得以下结果(这似乎更有可能):
<html><body><p style="color:red">TEXT</p></body></html>
那就很简单了
from lxml import etree
html = etree.Element("html")
body = etree.SubElement(html, "body")
p = etree.subElement(body, "p")
p.text = "TEXT"
p.set("style", "color:red")
print(etree.tostring(html))
from lxml import etree
html = etree.Element("html")
body = etree.SubElement(html, "body")
body.text = "TEXT"
body.set("p style", "color:red")
print(etree.tostring(html))
给我错误:ValueError:无效的属性名称 u'p style'
您不能在 XML 中包含带有 space 的属性,这就是 lxml
和 etree
的用途。 XML 规范说明什么是有效的属性名称 here.
如果您正在努力实现这一目标:
<html><body p style="color:red">TEXT</body></html>
您不能在 XML 中这样做。您可以在 HTML 中做类似的事情:空属性。有关详细信息,请参阅 the HTML5 specification。但是您不会使用上面编写的那种代码来获得该结果。
如果您试图获得以下结果(这似乎更有可能):
<html><body><p style="color:red">TEXT</p></body></html>
那就很简单了
from lxml import etree
html = etree.Element("html")
body = etree.SubElement(html, "body")
p = etree.subElement(body, "p")
p.text = "TEXT"
p.set("style", "color:red")
print(etree.tostring(html))