I have a large XML file and I want to extract some tags and write them in another xml file. I wrote this code:
import xml.etree.cElementTree as CE
tree = CE.ElementTree()
root = CE.Element("root")
i = 0
for event, elem in CE.iterparse('data.xml'):
if elem.tag == "ActivityRef":
print(elem.tag)
a = CE.Element(elem.tag)
root.append(elem)
elem.clear()
i += 1
if i == 200:
break
But I don't get the desired result, I got this:
<root>
<ActivityRef />
<ActivityRef />
<ActivityRef />
<ActivityRef />
...
</root>
instead of this:
<root>
<ActivityRef>
<Id>2008-12-11T20:43:07Z</Id>
</ActivityRef>
<ActivityRef>
<Id>2008-10-11T20:43:07Z</Id>
</ActivityRef>
...
</root>
Edit
Input file:
<?xml version="1.0" encoding="UTF-8"?>
<Folders>
<History>
<Running>
<ActivityRef>
<Id>2009-03-14T17:05:55Z</Id>
</ActivityRef>
<ActivityRef>
<Id>2009-03-13T06:12:42Z</Id>
</ActivityRef>
<ActivityRef>
<Id>2009-03-08T09:00:29Z</Id>
</ActivityRef>
<ActivityRef>
<Id>2009-03-04T19:39:39Z</Id>
</ActivityRef>
...
</Running>
</History>
</Folders>
And also I need to remove the element from the source file.