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
221 views
in Technique[技术] by (71.8m points)

python - insert list of elements in loop inside element builder in lxml

I have a XML body which was constructed using lxml.etree.E module. It looks like this -

E.TAGA(
    E.TAGB(
        E.TAGC(
            ...list goes here...
        )
    )
)

This method of construction cannot be altered.

I have a list of strings ["textA", "textB", "textC"] which have to be added to the xml under TAGC (as shown above) with each entry wrapped inside another tag TAGD. I have tried using fromStringlist but it doesn't work. Please help. Hope my question is clear.

This is how the final XML code should appear -

E.TAGA(
    E.TAGB(
        E.TAGC(
            E.TAGD(textA),
            E.TAGD(textB),
            E.TAGD(textC)
        )
    )
)

Here is the desired output -

<TAGA>
    <TAGB>
        <TAGC>
            <TAGD>textA</TAGD>
            <TAGD>textB</TAGD>
            <TAGD>textC</TAGD>
        </TAGC>
    </TAGB>
</TAGA>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

below (using core python XML lib)

import xml.etree.ElementTree as ET

d_data = ['T1', 'T2', 'T3']

a = ET.Element('A')
b = ET.SubElement(a, 'B')
c = ET.SubElement(b, 'C')
for text in d_data:
    temp = ET.SubElement(c, 'D')
    temp.text = text
ET.dump(a)

output

<?xml version="1.0" encoding="UTF-8"?>
<A>
   <B>
      <C>
         <D>T1</D>
         <D>T2</D>
         <D>T3</D>
      </C>
   </B>
</A>

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

...