使用lxml库在for循环中标记

时间:2017-09-18 12:29:13

标签: python openerp lxml odoo-8 odoo-9

from lxml import etree
def generate_header(self):
    root = etree.Element('TAG1',)
    for inv in self.env['account.invoice'].search([]):
        po_code = etree.SubElement(root, 'data').text = str(inv.id)
    return root

如何在for循环中添加另一个标记。如果我把root放在for循环中,那么它会为1条记录生成xml文件。我需要它看起来像这样。

<tag1>
   <tag2>
     <data>my data<data>
   </tag2>
</tag1>

我的代码我正在

        <tag1>
             <data>my data<data>
        </tag1>

我只是需要与tag1相同的标签才能进行循环

1 个答案:

答案 0 :(得分:0)

这适用于您想要的任意数量的标签:

from lxml import etree

def do(n_of_tags, inner_tag_name, inner_tag_text, starting_tag_num=1):
    i = starting_tag_num
    # create root outside loop
    root = etree.Element('tag{}'.format(i))
    parent = root
    i+= 1
    while i <= n_of_tags:
        # append next tag to parent and make the new tag parent
        parent.append(etree.Element('tag{}'.format(i)))
        parent = parent.getchildren()[0]
        i+= 1
    # add your own tag to last parent with text
    etree.SubElement(parent,inner_tag_name).text = inner_tag_text
    return root

r = do(2,'data','my data')
# just to see if it works
with open('test.xml','wb') as w:
    w.write(etree.tostring(r,pretty_print=True))