Python XML - 创建n个子元素

时间:2016-11-06 20:52:28

标签: python xml

如何创建n个SubElements?元素数量先前由给定值(计数)定义。所有元素中的元素名称和值都相同。 例如:

 <root>
      <selem>-9999</selem>
      <selem>-9999</selem>
      <selem>-9999</selem>
      <selem>-9999</selem>
              .
              .
              .
              n
 </root>

我试过像

这样的东西
 file_count = open('file_count.xml','r')
 data = file_count.read()
 file_count.close()
 dom = parseString(data)
 count = len(dom.getElementsByTagName('timePosition'))

 no_data = '-9999'
 top = etree.Element('root')
 children = [
     etree.SubElement(top, 'selem').text = no_data
     for i in xrange(count)
     ]
 top.extend(children)
 print etree.tostring(top)
 no_data_xml = etree.ElementTree(top)
 no_data_xml.write(new.xml')

TNX

2 个答案:

答案 0 :(得分:1)

您不能将诸如变量赋值之类的语句放在列表解析中。只需使用plain for循环:

for i in xrange(count):
    elem = etree.SubElement(top, 'selem')
    elem.text = no_data
    top.append(elem)

答案 1 :(得分:1)

SubElement会自动将元素添加到它的父元素中,因此不需要显式追加/扩展它们。所以不需要使用列表解析,只需使用for循环:

with open('file_count.xml','r') as file_count:
    data = etree.prase(file_count)
count = len(data.findall('.//timePosition'))

no_data = '-9999'
top = etree.Element('root')
for i in xrange(count):
    etree.SubElement(top, 'selem').text = no_data
 no_data_xml = etree.ElementTree(top)
 no_data_xml.write(new.xml')