lxml:在给定位置插入标签

lxml:在给定位置插入标签,第1张

lxml:在给定位置插入标签

您可以使用addnext()方法

from lxml import etreeXML= """<tag attrib1='I'>  <subtag1 subattrib1='1'>    <subtext>text1</subtext>  </subtag1>  <subtag3 subattrib3='3'>    <subtext>text3</subtext>  </subtag3></tag>"""parser = etree.XMLParser(remove_blank_text=True)tag = etree.fromstring(XML, parser)subtag1 = tag.find("subtag1")subtag2 = etree.Element("subtag2", subattrib2="2")subtext = etree.SubElement(subtag2, "subtext")subtext.text = "text2"subtag1.addnext(subtag2)   # Add subtag2 as a following sibling of subtag1print etree.tostring(tag, pretty_print=True)

输出:

<tag attrib1="I">  <subtag1 subattrib1="1">    <subtext>text1</subtext>  </subtag1>  <subtag2 subattrib2="2">    <subtext>text2</subtext>  </subtag2>  <subtag3 subattrib3="3">    <subtext>text3</subtext>  </subtag3></tag>

替代方法:

insert()
在根元素上使用:

subtag2 = etree.Element("subtag2", subattrib2="2")subtext = etree.SubElement(subtag2, "subtext")subtext.text = "text2"tag.insert(1, subtag2)   # Add subtag2 as the second child (index 1) of the root element


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5601849.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存