在python3中使用多个函数编写xml元素

2024-09-26 22:13:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在一个xml文件中编写一组元素,每两个元素都应该是空的,所以为了使代码更紧凑,我想我应该编写一个函数来写出空元素。当然,我无法生成这样的代码:

def makeOne():
   table=etree.SubElement(tables,'table')
   values = etree.SubElement(table,'values')

稍后在实际输入值的函数中调用它,因为我收集的文件没有加载到该函数中。我可能错了。我没有做太多的Python,所以我不知道是否有更优雅的方法来处理这个问题。为了清楚起见,这就是我的想法

def writeVals():
   tree = etree.parse('singleprog') 
   root = tree.getroot()
   tables = etree.SubElement(korjen[0], 'tables')
   makeOne()

很明显我想看到的是,我不能把这两个子元素放在writeVals()函数中,因为我需要在任意位置使用这段代码30次


Tags: 文件方法函数代码tree元素tablesdef
1条回答
网友
1楼 · 发布于 2024-09-26 22:13:35

这并不是真正的答案,但是你也可以使用^{}库,这是一种非常好的^{}工厂方法:

from lxml import etree
from lxml.builder import E

table = E.table(E.values)

etree.dump(table)

您将得到:

<table>
  <values/>
</table>

更进一步:

table = E.table(
    E.values("one"),
    E.values("two"),
    E.values("there"),
)

etree.dump(table)

您将得到:

<table>
  <values>one</values>
  <values>two</values>
  <values>there</values>
</table>

lxml简介:

The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API. The latest release works with all CPython versions from 2.6 to 3.6. See the introduction for more information about background and goals of the lxml project. Some common questions are answered in the FAQ.

相关问题 更多 >

    热门问题