Python 如何用字符串替换lxml中的元素

Python 如何用字符串替换lxml中的元素,python,lxml,Python,Lxml,我试图在lxml和python中找出如何用字符串替换元素 在我的实验中,我有以下代码: from lxml import etree as et docstring = '<p>The value is permitted only when that includes <xref linkend=\"my linkend\" browsertext=\"something here\" filename=\"A_link.fm\"/>, otherwise the v

我试图在lxml和python中找出如何用字符串替换元素

在我的实验中,我有以下代码:

from lxml import etree as et

docstring = '<p>The value is permitted only when that includes <xref linkend=\"my linkend\" browsertext=\"something here\" filename=\"A_link.fm\"/>, otherwise the value is reserved.</p>'

topicroot = et.XML(docstring)
topicroot2 = et.ElementTree(topicroot) 
xref = topicroot2.xpath('//*/xref')
xref_attribute = xref[0].attrib['browsertext']

print href_attribute
从lxml导入etree作为et
docstring='仅当包含时才允许该值,否则该值将保留。

' topicroot=et.XML(docstring) topicroot2=et.ElementTree(topicroot) xref=topicroot2.xpath('/*/xref') 外部参照属性=外部参照[0]。属性库['browsertext'] 打印href\u属性
结果是:“这里有些东西”

这是我在这个小示例中查找的浏览器文本属性。但我似乎不知道如何用我在这里捕获的属性文本替换整个元素

(我确实认识到,在我的示例中,我可能有多个外部参照,需要构造一个循环来正确地遍历它们。)

做这件事最好的方法是什么

对于那些想知道的人,我不得不这么做,因为链接实际上指向了一个由于我们不同的构建系统而不存在的文件

提前谢谢

试试这个(Python 3):

从lxml导入etree作为et
docstring='仅当包含时才允许该值,否则该值将保留。

' #获取根元素。 topicroot=et.XML(docstring) topicroot2=et.ElementTree(topicroot) #获取根元素的文本。这是一个字符串列表! topicroot2_text=topicroot2.xpath(“text()”) #获取外部参照元素。 xref=topicroot2.xpath('/*/xref')[0] xref_attribute=xref.attrib['browsertext'] #保存对p元素的参照,然后从中删除外部参照。 parent=xref.getparent() 父对象。删除(外部参照) #通过将字符串列表与 #提取属性值。 新文本=[topicroot2\u文本[0],外部参照属性,topicroot2\u文本[1]] parent.text=”“.加入(新文本) 打印(et.tostring(topicroot2))
输出:

b'<p>The value is permitted only when that includes something here, otherwise the value is reserved.</p>'
b'仅当此处包含某些内容时才允许该值,否则该值将保留。

'
预期的输出是什么?这正是我想要做的。谢谢我的思路是正确的,但无法确定如何删除该元素。令人惊叹的!
b'<p>The value is permitted only when that includes something here, otherwise the value is reserved.</p>'