如何在 python 中使用 libxml2 编写 xml 文件?

How to write an xml file using libxml2 in python?

我正在尝试使用 libxml2python3 中写入一个 xml 文件。我找不到任何关于 python 关于使用 libxml 写入文件的相关文档。当我尝试编写一个用 libxml2 解析的 xml 文件时,我收到错误:

xmlDoc has no attribute write

这里有人做过吗?我可以让它在 Etree 中正常工作,但 Etree 不会遵守我需要的属性顺序。

import libxml2



DOC = """<?xml version="1.0" encoding="UTF-8"?>

<verse>

  <attribution>Christopher Okibgo</attribution>

  <line>For he was a shrub among the poplars,</line>

  <line>Needing more roots</line>

  <line>More sap to grow to sunlight,</line>

  <line>Thirsting for sunlight</line>

</verse>

"""



doc = libxml2.parseDoc(DOC)

root = doc.children

print root

您可以使用 saveFile()saveFileEnc()。示例:

import libxml2

XML = """
<root a="1" b="2">XYZ</root>
"""

doc = libxml2.parseDoc(XML)

doc.saveFile("test.xml")
doc.saveFileEnc("test2.xml", "UTF-8")

我找不到 Python API 的任何好的文档。这是相应的 C 文档:http://xmlsoft.org/html/libxml-tree.html#xmlSaveFile.