带有文本值的 Python lxml 子元素? [英] Python lxml Subelement with text value?

查看:32
本文介绍了带有文本值的 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.

这篇关于带有文本值的 Python lxml 子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆