Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

python - lxml: insert tag at a given position

I have an xml file, similar to this:

<tag attrib1='I'>
  <subtag1 subattrib1='1'>
    <subtext>text1</subtext>
  </subtag1>
  <subtag3 subattrib3='3'>
    <subtext>text3</subtext>
  </subtag3>
</tag>

I would like to insert a new subElement, so the result would be something like this

<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>

I can append my xml file, but then the new elements will be inserted at the end. How can I force python lxml to put it into a given position?

Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the addnext() method:

from lxml import etree

XML= """
<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 subtag1

print etree.tostring(tag, pretty_print=True)

Output:

<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>

Alternative: use insert() on the root element:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...