Python XML子元素中的变量

Python XML子元素中的变量,python,xml,tree,elementtree,Python,Xml,Tree,Elementtree,我正在考虑使用Python代码来创建动态xml ETREE子元素 我有一个分层标题,描述书中的平静,如下所示: <Books> <Booktype List= "Story > Fiction > Young"> #here the rest of book text </Booktype> <Booktype List= "Science > Math > Young"> #here the rest of book te

我正在考虑使用Python代码来创建动态xml ETREE子元素

我有一个分层标题,描述书中的平静,如下所示:

<Books>
<Booktype List= "Story > Fiction > Young">
#here the rest of book text
</Booktype>
<Booktype List= "Science > Math > Young">
#here the rest of book text
</Booktype>
</Books>
我得到了这个坏结果:

'<Books><Booktype><Story /><Story /><Story /><Fiction /><Fiction /><Young /><Young /><Story /><Story /><Fiction /><Fiction /><Young /><Young /></Booktype></Books>'
“”

如果要嵌套列表元素,则必须保留对上一个元素的引用,以便可以将子元素添加到列表元素中,而不是添加到
Booktype
元素中。请参见示例中的变量
current

从xml.etree导入ElementTree作为ET
xml_字符串=“”
#这是书的其余部分
#这是本书第2部分的剩余部分
'''
xml=ET.fromstring(xml\u字符串)
对于xml.findall(“booktype”)中的booktype:
types=map(lambda x:x.strip(),booktype.get('List').split('>'))
当前=书籍类型
对于类型中的t:
电流=ET.子元素(电流,t)
current.text=booktype.text
booktype.text=“”
del booktype.attrib['List']
打印ET.tostring(xml,'utf-8')
给我一个结果:

<Books>
<Booktype><Story><Fiction><Young>
#here the rest of book text
</Young></Fiction></Story></Booktype>
<Booktype><Science><Math><Young>
#here the rest of book text 2
</Young></Math></Science></Booktype>
</Books>

如果要嵌套列表元素,则必须保留对上一个元素的引用,以便可以将子元素添加到列表元素中,而不是添加到
Booktype
元素中。请参见示例中的变量
current

从xml.etree导入ElementTree作为ET
xml_字符串=“”
#这是书的其余部分
#这是本书第2部分的剩余部分
'''
xml=ET.fromstring(xml\u字符串)
对于xml.findall(“booktype”)中的booktype:
types=map(lambda x:x.strip(),booktype.get('List').split('>'))
当前=书籍类型
对于类型中的t:
电流=ET.子元素(电流,t)
current.text=booktype.text
booktype.text=“”
del booktype.attrib['List']
打印ET.tostring(xml,'utf-8')
给我一个结果:

<Books>
<Booktype><Story><Fiction><Young>
#here the rest of book text
</Young></Fiction></Story></Booktype>
<Booktype><Science><Math><Young>
#here the rest of book text 2
</Young></Math></Science></Booktype>
</Books>
<Books>
<Booktype><Story><Fiction><Young>
#here the rest of book text
</Young></Fiction></Story></Booktype>
<Booktype><Science><Math><Young>
#here the rest of book text 2
</Young></Math></Science></Booktype>
</Books>