我正在使用lxml生成一个大型XML文件。文件中使用的标签之一是“lambda”,所以我不能像往常那样定义它。 (不,我不能改变标签的名称)
代码:
import lxml.etree as ETree
import lxml.builder as lxmlBuilder
E = lxmlBuilder.ElementMaker()
root = E.root
lbd = E.lambda #error since lambda is reserved
myTree = root(
lbd('1')
)
print ETree.tostring(myTree, pretty_print=True)
预期结果:
<root>
<lambda>1</lambda>
</root>
由于是这种情况,我只想手动输入“lambda”标签。但是,当我尝试这样做时,“lambda”周围的“小于”或“大于”符号被转换为&amp; lt和&amp; gt。 代码:
E = lxmlBuilder.ElementMaker()
root = E.root
lbd = "<lambda>%f</lambda>" % 1 #by hand
myTree = root(
lbd
)
print ETree.tostring(myTree, pretty_print=True)
结果:
<root>
<lambda>1.0000</lambda>
</root>
如何防止&lt;和&gt;像这样被转换的符号?
答案 0 :(得分:2)
您可以使用lbd = getattr(E, 'lambda')
代替lbd = E.lambda
来克服由于保留关键字造成的限制。
>>> import lxml.etree as ETree
>>> import lxml.builder as lxmlBuilder
>>> E = lxmlBuilder.ElementMaker()
>>> root = E.root
>>> lbd = getattr(E, 'lambda')
>>> myTree = root(lbd('1'))
>>> ETree.tostring(myTree, pretty_print=True)
b'<root>\n <lambda>1</lambda>\n</root>\n'