简体   繁体   中英

How do I change the order of a child element in lxml objectify?

I have XML where the order of the child elements determines their z-order for display purposes. I use lxml.objectify to operate on the XML.

How do I change the position of a child element in objectify?

Eg change:

<canvas>
  <shape a>
  <shape b>
  <shape c>
</canvas>

To:

<canvas>
  <shape b>
  <shape a>
  <shape c>
</canvas>

canvas.shape will be a list, so just modify the list:

from lxml import objectify, etree

canvas = objectify.fromstring('''
    <canvas>
      <shape name="a" />
      <shape name="b" />
      <shape name="c" />
    </canvas>
''')

canvas.shape = [canvas.shape[1], canvas.shape[0], canvas.shape[2]]

print etree.tostring(canvas, pretty_print=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM