开发者

lxml: How to make new Element tree from given element in a tree

I am using lxml for parsing xml data. I have to divide the xml at various nodes and write the data in each of these subtrees to separate files. lxml provides the write() method开发者_运维技巧 in _ElementTree class which conveniently writes the xml represented by the parse tree to a file.

So if I can make tree (_ElementTree object) by the root node of the subtree of the given node then I can easily use write() method. How to do that.


Sorry to bother, I found the answer. Its:

new_tree = etree.ElementTree(node_in_tree)


You don't need to create a new ElementTree in order to write an element and its contents to a file, you can just write the result of etree.tostring(element), e.g.:

from lxml import etree

with open("whatever.xml") as fp:
    tree = etree.parse(fp)
    i = 0
    for node in tree.xpath('//section'):
        output_filename = "output-%d.xml" % (i,)
        with open(output_filename,"w") as fp:
            fp.write(etree.tostring(node))
        i += 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜