python - XML 子元素中的变量

标签 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 text
</Booktype>
</Books>

如何获取像这样的分层 xml 标签:

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

这是我的代码:

import re
import xml.etree.ElementTree as ET
from xml.etree import ElementTree


List= "Story>Fiction>Young"
List = List.split('>')
root = ET.Element('Books')
Booktype =ET.SubElement(root,'Booktype')

for l in List:
  ND = ET.SubElement(Booktype,str(l))
  Booktype.append(ND)

tree = ET.ElementTree(root)
ElementTree.tostring(root,'utf-8')

我得到了这个糟糕的结果:

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

最佳答案

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

from xml.etree import ElementTree as ET

xml_string = '''<Books>
<Booktype List= "Story > Fiction > Young">
#here the rest of book text
</Booktype>
<Booktype List= "Science > Math > Young">
#here the rest of book text 2
</Booktype>
</Books>
'''

xml = ET.fromstring(xml_string)
for booktype in xml.findall('Booktype'):
    types = map(lambda x: x.strip(), booktype.get('List').split('>'))
    current = booktype
    for t in types:
        current = ET.SubElement(current, t)
    current.text = booktype.text
    booktype.text = ''
    del booktype.attrib['List']
print 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>

如果您想创建一个全新的结构,您可以这样做:

xml = ET.fromstring(xml_string)
root = ET.Element('Books')
for booktype in xml.findall('Booktype'):
    current = ET.SubElement(root, 'Booktype')
    for t in map(lambda x: x.strip(), booktype.get('List').split('>')):
        current = ET.SubElement(current, t)
    current.text = booktype.text
print ET.tostring(root, 'utf-8')

关于python - XML 子元素中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18172482/

相关文章:

python - plt.plot()、object.plot() 之间有什么区别

javascript - 关于如何处理 javascript 小部件的想法?

xml - vba excel : need to load an xml file and write specific values (got from current) excel then save it

java - 在 xml 文件中使用字符串变量 (android studio)

select - extjs 4 树通过其内部 id(而不是通过记录索引)选择特定节点

javascript - 我想在 D3.js TreeMap 中的链接上添加文本

python - pyparsing nestedExpr 和嵌套括号

python - 如何禁用 Matplotlib 中的键盘快捷键?

python - 错误! 'int' 对象没有属性 'append'

python - 深度python字典递归