how to create a sub-element through variable in py

2020-02-15 06:43发布

问题:

My code is:

import xml.etree.ElementTree as ET
from lxml import etree
var1 = '<name>This is my text</name>'
page = etree.Element('first')
doc = etree.ElementTree(page)
second = etree.SubElement(page, 'second')
second.text = var1
doc.write('a.xml', xml_declaration=True, encoding='utf-8')

My output is:

<?xml version='1.0' encoding='UTF-8'?>
<first><second>&lt;name&gt;This is my text&lt;/name&gt;</second></first>

My Desired Output is:

<?xml version='1.0' encoding='UTF-8'?>
<first><second><name>This is my text</name></second></first>

Actually, I want to create sub-element through variable and I don't know how many elements are available in our variable. this is only for test purpose so please take care of this.

回答1:

It is not possible to create a subelement by supplying it as a string of XML markup. The <name> element has to be created using SubElement, just like <second>.

The following code produces the desired output:

from lxml import etree

page = etree.Element('first')
second = etree.SubElement(page, 'second')
name = etree.SubElement(second, 'name')
name.text = "This is my text"

doc = etree.ElementTree(page)
doc.write('a.xml', xml_declaration=True, encoding='utf-8')

An alternative is to parse the <name>This is my text</name> string into an Element object and append it to the parent:

from lxml import etree

var1 = '<name>This is my text</name>'
name = etree.fromstring(var1)

page = etree.Element('first')
second = etree.SubElement(page, 'second')
second.append(name)

doc = etree.ElementTree(page)
doc.write('b.xml', xml_declaration=True, encoding='utf-8')