我有一个大XML文件,我想提取一些标签并将其写入另一个XML文件。我写了此代码:
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
但我没有得到所需的结果,我得到了:
<root>
<ActivityRef />
<ActivityRef />
<ActivityRef />
<ActivityRef />
...
</root>
而不是这样:
<root>
<ActivityRef>
<Id>2008-12-11T20:43:07Z</Id>
</ActivityRef>
<ActivityRef>
<Id>2008-10-11T20:43:07Z</Id>
</ActivityRef>
...
</root>
编辑
输入文件:
<?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>
,我还需要从源文件中删除元素。
使用xpath
import xml.etree.ElementTree as ET
data = '''<?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>'''
root = ET.fromstring(data)
# 'activities' contains the elements you are looking for
activities = root.findall('.//ActivityRef')