本文介绍了如何通过python 3.6.5中的变量创建子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是:

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')

我的输出是:

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

我想要的输出是:

<?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.

推荐答案

无法通过将子元素作为XML标记字符串提供来创建子元素.就像<second>一样,必须使用SubElement创建<name>元素.

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')

另一种方法是将<name>This is my text</name>字符串解析为Element对象,并将其附加到父对象:

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')

这篇关于如何通过python 3.6.5中的变量创建子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:20