Elementtree:提取节点并写入文件

时间:2017-06-27 03:52:10

标签: python xml elementtree

我正在寻找一种从树中提取节点的方法,使其成为新树并将其写入文件。

<content>
    <book id="A">
        <chapter />
        <chapter />
    </book>
    <book id="B">
    <book id="C">
</content>

在这个例子中,它应该是book @ a,它应该成为以<book>为根元素的a.xml:

<book id="A">
   <chapter />
   <chapter />
</book>

我使用ElementTree。我的第一个尝试是在for循环中找到所有书@ a并使用.write或.tostring,但这根本不起作用,或者它产生了一个带有内容的新xml [&lt; Element&#39;本书&#39;在0x00000000031DD1D8&gt;]:)

1 个答案:

答案 0 :(得分:0)

您可以找到包含bookfind的第一个元素findall

import xml.etree.ElementTree as ET
data_as_string="""
<content>
    <book id="A">
        <chapter />
        <chapter />
    </book>
    <book id="B"></book>
    <book id="C"></book>
</content>
"""
root = ET.fromstring(data_as_string)
print ET.tostring(root.findall('book')[0])
print ET.tostring(root.find('book'))

它将打印:

<book id="A">
        <chapter />
        <chapter />
    </book>

<book id="A">
        <chapter />
        <chapter />
    </book>
相关问题