带有文本值的 Python lxml 子元素?
是否可以通过某种方式创建具有默认文本值的元素?所以我不需要这样做?
Is it possible to somehow create element with default text value? So I would not need to do it like this?
from lxml import etree
root = etree.Element('root')
a = etree.SubElement(root, 'a')
a.text = 'some text' # Avoid this extra step?
我的意思是您可以在SubElement中指定属性,但是我看不到在其中指定文本的方法.
I mean you can specify attributes in SubElement, but I don't see a way to specify text in it.
我认为没有内置的方法可以执行此操作,但是如果您发现自己执行了很多次,最好编写一个函数来封装创建子元素和设置文本.示例-
I don't think there is a builtin way to do that, but if you find yourself doing that many times, it may be better to write a function that encapsulates creating the sub element and setting the text. Example -
def create_SubElement(_parent,_tag,attrib={},_text=None,nsmap=None,**_extra):
result = etree.SubElement(_parent,_tag,attrib,nsmap,**_extra)
result.text = _text
return result
然后将您的元素创建为-
And then create your element as -
a = create_SubElement(root,'a',_text="Some text")
请注意,这样您将无法使用关键字参数创建名称为 _text
的属性,为此您需要使用 attrib
关键字参数.
Please note, with this you would not be able to create attribute with name _text
using keyword arguments, you would need to use attrib
keyword argument for that.