[英]How do I create a namespaced element with lxml?
I'm using lxml to generate an RSS feed that is ultimately used as a podcast.我正在使用 lxml 生成最终用作播客的 RSS 提要。 That means I need to add namespaced elements like
<itunes:duration>
and <itunes:subtitle>
.这意味着我需要添加像
<itunes:duration>
和<itunes:subtitle>
这样的命名空间元素。 But I'm having so much trouble trying to figure out how to create elements like these with lxml dynamically.但是我在试图弄清楚如何用 lxml 动态地创建这样的元素时遇到了很多麻烦。
If I simply try:如果我只是尝试:
from lxml import etree
element = etree.Element("itunes:duration")
I get this:我明白了:
ValueError: Invalid tag name 'itunes:duration'
Next I tried this and got a little closer:接下来我尝试了这个并离得更近了一点:
from lxml import etree
etree.register_namespace("itunes", "http://www.itunes.com/dtds/podcast-1.0.dtd")
element = etree.Element("{itunes}duration")
print(etree.tostring(element).decode("utf-8"))
However that resulted in this output:然而,这导致了这个 output:
<ns0:duration xmlns:ns0="itunes"/>
So while that's better than an exception, it's still obviously not right.因此,虽然这比例外要好,但显然仍然是不对的。 How can I create an element with an
itunes:
prefix in the tag name?如何在标签名称中创建带有
itunes:
前缀的元素?
Try using etree.QName()
...尝试使用
etree.QName()
...
from lxml import etree
etree.register_namespace("itunes", "http://www.itunes.com/dtds/podcast-1.0.dtd")
element = etree.Element(etree.QName("http://www.itunes.com/dtds/podcast-1.0.dtd", "duration"))
print(etree.tostring(element).decode("utf-8"))
prints...印刷...
<itunes:duration xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"/>
You could also just use Clark notation...你也可以只使用克拉克符号......
element = etree.Element("{http://www.itunes.com/dtds/podcast-1.0.dtd}duration")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.