2

I am attempting to write an xml file in python3 using libxml2. I cannot find any relevant documentation regarding python about writing files with libxml. When I attempt to write an xml file parsed with libxml2 I get the error:

xmlDoc has no attribute write

Anyone here done this before? I can get it to work in Etree just fine but Etree will not respect the attribute order that I need.

4
  • 2
    Are you able to use lxml? It uses libxml2 (and libxslt). It's also easy to write to a file by using the write() method of the ElementTree object. Commented Jul 16, 2019 at 2:54
  • Sadly not :( It's an older linux system for work and I can't get lxml on to the system. Commented Jul 16, 2019 at 14:32
  • Please discuss your overall needs and not the specific tools. Python maintains xml.etree.ElementTree as part of its standard library and can easily develop XML files. Commented Jul 16, 2019 at 15:11
  • For my specific need and python version I needed a way to parse the xml files while respecting the attribute order, I am not able to download anything else nor perform a patch of etree, I'm basically limited to libxml2. I just cannot seem to write files parsed by it. Commented Jul 16, 2019 at 15:32

2 Answers 2

4

You can use saveFile() or saveFileEnc(). Example:

import libxml2

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

doc = libxml2.parseDoc(XML)

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

I could not find any good documentation for the Python API. Here is the corresponding C documentation: http://xmlsoft.org/html/libxml-tree.html#xmlSaveFile.

Sign up to request clarification or add additional context in comments.

Comments

1
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

4 Comments

This does re-print the XML file, but how would you take this output and rewrite it as an actual .XML file in your path?
You can write file = open("filename.xml", "w+") then start writing in it using file.write()
That gives the same error I mentioned above, the 'xmlDoc object has no attribute 'write''.
Sorry I haven't really dealt with XML files but you can read this article that I found helpful for your situation stackabuse.com/reading-and-writing-xml-files-in-python there are all examples you may look for using a module for it to work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.