【问题标题】:Python: Write XML Contents to a file using lxml libraryPython:使用 lxml 库将 XML 内容写入文件
【发布时间】:2022-02-18 05:33:28
【问题描述】:

我有一个将 xml 字符串写入文件的 Python 函数。代码如下:

我的 file_contents 是一个字符串,如下:

<A>Some Text</A>
<B>Some other Text</B>

我想把这个字符串附在里面,并将 xml 标题 : 添加到文件中。我似乎无法弄清楚这一点。

from lxml import etree

def create_or_overwrite_file(file_name, file_contents):
    try:        
        print('file contents to be written: %s' % file_contents)

        '''
        #root = etree.fromstring(file_contents) #this line definitely fails because file_contents is NOT a valid XML

        #print('root: %s' % str(root))
        #newroot = etree.Element('RootElement')
        #newroot.insert(0, root)
        #print('newroot: %s' % newroot)
        #new_file_contents = etree.tostring(newroot)
        #print('NewFileContents: %s' % str(new_file_contents))
         '''

        root = etree.fromstring(file_contents).getroot()
        et = etree.ElementTree(root)
        with open(str(file_name), "wb") as f:
            et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)
            print('wrote file_contents to %s' % str(file_name))
    except Exception as f:
        print(str(f))

我似乎无法让这段代码工作。任何帮助表示赞赏。

【问题讨论】:

  • 它做什么或不做什么?
  • file_name 已经是一个字符串。打电话str(file_name)没有意义。
  • “不工作”不是对问题的有用描述。请准确澄清问题。错误?不想要的结果?此外,file_contents 中显示的标记是 not XML,因为它没有根。因此,lxml 在尝试解析时应该会出错。
  • @Parfait:根据您的说法,无法使用 lxml 库将我的 xml 包含在根元素中。我必须自己添加标签元素,例如 '' + file_contents + ''
  • 同样,该标记是 not XML。根据定义,XML 是格式良好的(即,在其他规则中具有根)。检查该标记是如何生成的。它可以由字符串构建。请参阅:What's so bad about building XML with string concatenation? 考虑使用 DOM 库来构建 XML,例如 Python 的 lxml

标签: python lxml


【解决方案1】:

如果您从字符串中解析(而不是从文件中读取)。然后fromstring 已经返回根。你不需要.getroot() 电话:

    root = etree.fromstring(file_contents)

通过这一更改,您的代码对我有效。

现在,尚不清楚您为什么要这样做。如果file_contents 已经是XML,因为它必须这样才能工作,那么为什么不只是open(file_name).write(file_contents)?为什么要解码 XML 然后重新编码?


跟进

如果你想要的只是一个包装器,那么这会起作用:

def create_or_overwrite_file(file_name, file_contents):
    f = open(file_name,'w')
    print( '<?xml version="1.0"?>\n<root>', file=f )
    f.write(file_contents)
    print( '</root>', file=f )

不涉及lxml 可能更有效。更有意义的地方取决于您。

【讨论】:

  • 我想将 XML Header 写入文件。 file_contents 中没有标题。事实上,它没有根元素。我还没有弄清楚如何将“file_contents”包含在根元素中并在顶部添加标题。我将修改我的代码以更好地描述这一点。
  • 您的代码唯一的一点是,如果写入失败,用户将得到一个格式错误的 xml 文件。
  • 技术上是正确的,但实际上,这样的写入不会失败。如果第一个print 成功了,那么以后所有的都会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多