创建另一个节点子元素

时间:2017-01-25 00:26:38

标签: python lxml elementtree

我正在尝试在<Item>父块中添加<Items>块。例如:

<Items>
    <Item>...data...</Item>
    <Item>...data...</Item>
    <Item>...data...</Item>
</Items>

这是我到目前为止所做的:

>>> from lxml.etree import Element
>>> items=Element('Items')
>>> item=Element('Item')

如何在项目下添加项目?我试图做的是:

>>> SubElement(items, item)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lxml.etree.pyx", line 2935, in lxml.etree.SubElement (src/lxml/lxml.etree.c:67070)
  File "apihelpers.pxi", line 175, in lxml.etree._makeSubElement (src/lxml/lxml.etree.c:15221)
  File "apihelpers.pxi", line 1498, in lxml.etree._getNsTag (src/lxml/lxml.etree.c:27720)
  File "apihelpers.pxi", line 1516, in lxml.etree.__getNsTag (src/lxml/lxml.etree.c:27870)
  File "apihelpers.pxi", line 1393, in lxml.etree._utf8 (src/lxml/lxml.etree.c:26460)
TypeError: Argument must be bytes or unicode, got '_Element'

1 个答案:

答案 0 :(得分:2)

您可以使用Element class.append()方法:

>>> from lxml.etree import Element, tostring
>>> items = Element('Items')
>>> item = Element('Item')
>>> item.text = "foo"
>>> items.append(item)
>>> print(tostring(items, pretty_print=True))
<Items>
  <Item>foo</Item>
</Items>