代码的目的是将 XML 块插入到 XML 基本结构中以创建最终的 XML 输出。
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import XMLParser
base_tree = ET.parse('base_structure_01.XML')
base_root = base_tree.getroot()
specification = base_tree.find('specification')
applicability = specification.find('applicability')
entity_tree = ET.parse('entity_structure_01.XML')
entity_root = entity_tree.getroot()
ET.indent(entity_root,space =" ",level=3)
applicability.append(entity_root)
base_tree.write('output.xml')
base_struct_01.XML 的内容:
<ids>
<specification>
<applicability>
</applicability>
<requirements>
</requirements>
</specification>
</ids>
entity_struct_01.XML 的内容:
<entity>
<name>
<simpleValue>name</simpleValue>
</name>
<predefinedtype>
<simpleValue>predefinedtype</simpleValue>
</predefinedtype>
</entity>
我想要成为输出:
<ids>
<specification>
<applicability>
<entity>
<name>
<simpleValue>name</simpleValue>
</name>
<predefinedtype>
<simpleValue>predefinedtype</simpleValue>
</predefinedtype>
</entity>
</applicability>
<requirements>
</requirements>
</specification>
</ids>
当前输出是什么:
<ids>
<specification>
<applicability>
<entity>
<name>
<simpleValue>name</simpleValue>
</name>
<predefinedtype>
<simpleValue>predefinedtype</simpleValue>
</predefinedtype>
</entity></applicability>
<requirements>
</requirements>
</specification>
</ids>
问题:
<entity>
未正确缩进</entity>
与</applicability>
我知道还有其他选项可以缩进文本,我只是想知道使用 xml.etree.ElementTree 是否可以轻松解决这个问题。
感谢您的宝贵时间
如果您在
indent()
之后在整棵树上应用append()
,它就会起作用。
更换
ET.indent(entity_root,space =" ",level=3)
applicability.append(entity_root)
这样:
applicability.append(entity_root)
ET.indent(base_root,space =" ")