我正试图用Python将一个XML分割成多个XML文件。我发现代码只分割了第一个实例的主题。我试着用
findall
代替
find
,但似乎并不奏效。我是Python的新手,还没有学好语法。我正在使用Python 3。
我的XML文件是这种模式。
<?xml version="1.0" encoding="UTF-8"?>
<topic id = "topic1">
<title>ABC</title>
<p>This is topic1.</p>
</body>
</topic>
<topic id = "topic2">
<title>Test / xyz</title>
<section> <title>Section title</title>
<p>This is topic 2. </p>
</section>
</topic>
</dita>
我需要的输出。
脚本必须找到<topic>
标签并将内容分割成独立的XML。
ABC.xml
Test.xml
ABC.xml
<?xml version="1.0" encoding="UTF-8"?>
<topic id = topic1>
<title>ABC</title>
<p>This is topic1.</p>
</topic>
Test.xml
<?xml version="1.0" encoding="UTF-8"?>
<topic id = topic2>
<title>Test</title>
<section> <title>Section title</title>
<p>This is topic 2. </p>
</section>
</topic>
My code:
import xml.etree.ElementTree as ET
tree = ET.iterparse('file.xml', events=('end', ))
index = 0
for event, elem in tree:
if elem.tag == 'topic':
index += 1
title = elem.find('title').text