0

I am using lxml with

tree.write(xmlFileOut, pretty_print = True, xml_declaration = True, encoding='UTF-8'

to write out my opened and edited xml file, but I absolutely need to have the xml declaration as

<?xml version=“1.0” encoding=“UTF-8”?> 

and NOT

<?xml version='1.0' encoding='UTF-8'?>

Now I know they are exactly the same when it comes to xml, but I am dealing with a very tricky customer who absolutely has to have " in the declaration and not '. I have searched everywhere but can't find the answer.

Could I create it and add it in myself to the head of the xml somehow?

Could I tell lxml that this is what I need as an xml declaration?

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
speedyrazor
  • 3,127
  • 7
  • 33
  • 51
  • Did you really mean to use `“` and `”` (typographical open/close quotes) or do you really mean `"`? – Jim Garrison Jun 28 '13 at 22:19
  • Yes I mean what is in the question. – speedyrazor Jun 29 '13 at 06:35
  • That would not be valid XML, and it is unlikely you can get your XML processor to create it. The only solution is to write it yourself prior to writing the XML and suppress the declaration from lxml. – Jim Garrison Jun 29 '13 at 06:38
  • Hi Jim, this sounds like a solution. Any chance you could point me in the right direction when it comes to your solution please? – speedyrazor Jun 30 '13 at 14:48

2 Answers2

2

This is a site for coding questions, not a site for advice in dealing with tricky customers. Your customer is wrong; your problem is political/commercial, not technical.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • OK, so put another way.... Is there a way to add a line of non xml code to line 1 of an xml document then save it using lxml? – speedyrazor Jun 29 '13 at 06:10
  • Of course it's do-able, it's a text file so you can create it with text-based tools. But it becomes your responsibility to get the encoding right, etc. – Michael Kay Jun 29 '13 at 07:49
0

XML allows single and double quotes, see Common Syntactic Constructs, Literals. Depends on the used xml processor, what is used. Same question 11years ago. See also the discussion in the python forum for version 3.7.

# single quoting in xml declaration
from lxml import etree
from io import StringIO

xml = '<root>tree</root>'
f = StringIO(xml)

tree = etree.parse(f)
root = tree.getroot()

xmlFileOut = "out.xml"

tree.write(xmlFileOut, pretty_print=True, xml_declaration = True, encoding="UTF-8")

# double quoting in xml declaration
from xml.dom import minidom
xmlDom = minidom.parse("out.xml")

prettyXML = xmlDom.toprettyxml(encoding="UTF-8")

with open("out_min.xml", mode="wb") as file:
    file.write(prettyXML)
Hermann12
  • 1,709
  • 2
  • 5
  • 14