Cut out XML subtree
Andreas Perstinger
andipersti at gmail.com
Wed Aug 29 13:31:52 EDT 2012
On Wed, 29 Aug 2012 18:17:18 +0200
Florian Lindner <mailinglists at xgm.de> wrote:
> I want to cut out an XML subtree like that:
[snip]
> Is there a way I can do that using etree or DOM? The first is
> prefered...
Python 3.2.2 (default, Sep 5 2011, 22:09:30)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.etree.ElementTree as etree
>>> test = """
... <root attribute="foobar">
... <subA>
... <section1>Element A.1</section1>
... <section2>Element A.2</section2>
... </subA>
... <subB>
... <section1>Element B.1</section1>
... <section2>Element B.2</section2>
... </subB>
... </root>"""
>>> tree = etree.fromstring(test)
>>> subA = tree.find("subA")
>>> tree.remove(subA)
>>> new = etree.tostring(tree, encoding="unicode")
>>> print(new)
<root attribute="foobar">
<subB>
<section1>Element B.1</section1>
<section2>Element B.2</section2>
</subB>
</root>
Bye, Andreas
More information about the Python-list
mailing list