当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Insert xml node in specific location

问题描述:

I would like to build the following xml:

<Item>

<Name>Hello</Name>

<Date>2014-01-01</Date>

<Hero>1</Helo>

</Item>

Given the following code structure, how would I insert the <Date> node before the hero node?

item = etree.SubElement(self.xml_node, 'Item')

etree.SubElement(item, 'Name').text = 'Hello'

etree.SubElement(item, 'Hero').text = 1

# Now, how to insert the 'Date' element before the Hero element?

网友答案:

Using etree.SubElement always appends the subelement to the end of the parent item. So instead, to insert a new element at a particular location, use item.insert(pos, subelement):

import lxml.etree as etree
xml_node = etree.Element("node")
item = etree.SubElement(xml_node, 'Item')
etree.SubElement(item, 'Name').text = 'Hello'
etree.SubElement(item, 'Hero').text = '1'
etree.SubElement(item, 'Date').text = '2014-01-01'
item.insert(1, item[-1])
print(etree.tostring(xml_node, pretty_print=True))

yields

<node>
  <Item>
    <Name>Hello</Name>
    <Date>2014-01-01</Date>
    <Hero>1</Hero>
  </Item>
</node>

Each node in an ElementTree can occur at only one place. So although

etree.SubElement(item, 'Date').text = '2014-01-01'

places the <Date> node at the end of <item>,

item.insert(1, item[-1])

moves the last node in item, i.e. the <Date> node, to position 1 (making it the second child in <Item>).

网友答案:

etree elements behave like lists, so just use .insert():

>>> from xml.etree import ElementTree as etree

>>> parent = etree.Element('parent')

>>> etree.SubElement(parent, 'child1')
<Element 'child1' at 0x108797048>

>>> etree.SubElement(parent, 'child2')
<Element 'child2' at 0x108797188>

>>> el = etree.Element('child-one-and-a-half')
>>> parent.insert(1, el)

>>> etree.dump(parent)
<parent><child1 /><child-one-and-a-half /><child2 /></parent>
分享给朋友:
您可能感兴趣的文章:
随机阅读: