using fromstring() with lxml prefixes

一笑奈何 提交于 2019-12-08 05:35:58

问题


I have a variable ele. I'm trying to append a child node onto ele that contains a namespace prefix (called style) in its tag. ele seems to be aware of this prefix, as the line:

print(ele.nsmap['style'])

outputs

urn:oasis:names:tc:opendocument:xmlns:style:1.0

But when I try to run

ele.append(etree.fromstring('<style:style />'))

I get the error

lxml.etree.XMLSyntaxError: Namespace prefix style on style is not defined

What am I missing here?


回答1:


etree.fromstring('<style:style />') throws an error because <style:style /> is a small XML document that is not namespace-well-formed.

You have to declare the namespace in the document if you want to provide it as an argument to fromstring():

etree.fromstring('<style:style xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" />')


来源:https://stackoverflow.com/questions/24876855/using-fromstring-with-lxml-prefixes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!