将子元素添加到子元素lxml

时间:2017-11-15 19:13:33

标签: python xml lxml

我正在使用lxml来尝试输出以下xml代码:

<annotation>
    <folder>images</folder>
    <filename>IMG_8111.JPG</filename>
    <size>
        <width>400</width>
        <height>400</height>
    </size>
    <segmented>0</segmented>
    <object>
        <name>Bottle</name>
        <bndbox>
            <xmin>16</xmin>
            <ymin>71</ymin>
            <xmax>390</xmax>
            <ymax>323</ymax>
        </bndbox>
    </object>
</annotation>

我正在使用this教程来学习如何根据我的需要实现lxml。我面临的问题是我想要的输出有subelements to subelements。例如 - <annotation>是我的主要元素,然后<folder><filename><size>是子元素,但是<height><width>' are subelements to the`子元素。如何使用lxml实现这一点。到目前为止,我有以下内容:

from lxml import etree
import xml.etree.cElementTree as ET


root = etree.Element("annotation")
etree.SubElement(root, "folder").text = "Child 1"
etree.SubElement(root, "filename").text = "Child 2"
size = etree.SubElement(root, "size").text = "Child 3"
etree.SubElement(size, "width").text = "Child 4"


with open ('xmltree.xml', 'wb') as f:
    f.write(etree.tostring(root, pretty_print = True))

但它会引发以下错误:

 etree.SubElement(size, "width").text = "Child 4"
TypeError: Argument '_parent' has incorrect type (expected lxml.etree._Element, got str)

请帮我解决我做错了什么以及如何继续。

2 个答案:

答案 0 :(得分:1)

您的变量大小具有类型字符串,因为它具有&#34;子3&#34;值。你应该这样做:

size = etree.SubElement(root,"size")
size.text = "child 3" 
etree.SubElement(size, "width").text="child 4"

答案 1 :(得分:1)

为了按照您的预期评估size = etree.SubElement(root, "size").text = "Child 3",它必须被解释为:

(size = etree.SubElement(root, "size")).text = "Child 3"

在Python中,您无法在表达式中执行赋值。相反,Python解释它的方式是:

size = "Child 3"
etree.SubElement(root, "size").text = "Child 3"

您可以使用两个单独的行重写代码以获得所需的结果:

size = etree.SubElement(root, "size")
size.text = "Child 3"

查看lxml API后,它似乎不是一种既可以创建元素又可以在一行中为text属性赋值的方法。