2

Looking at the Python SAX documentation I only see reading XML using SAX. But I would like to write it.
I figured out how to do that in Java a while ago:

 public void renderXML(OutputStream out) {
      PrintWriter pw = new PrintWriter(out);
      StreamResult streamResult = new StreamResult(pw);
      SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
      TransformerHandler hd = tf.newTransformerHandler();
      Transformer serializer = hd.getTransformer();
      serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      serializer.setOutputProperty(OutputKeys.METHOD,"xml");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes"); // So it looks pretty in VI
      hd.setResult(streamResult);
      hd.startDocument();
      AttributesImpl atts = new AttributesImpl();
      atts.addAttribute("", "", "someattribute", "CDATA", "test");
      atts.addAttribute("", "", "moreattributes", "CDATA", "test2");
      hd.startElement("", "", "MyTag", atts);
      String curTitle = "Something inside a tag";
      hd.characters(curTitle.toCharArray(), 0, curTitle.length());
      hd.endElement("", "", "MyTag");
      hd.endDocument();
   }

What would be the Python equivalent? I checked an answer on SO using ElementTree - but that is rather the DOM way to do things (and problematic for really large output). Another question is un-answered. Or: what is the better approach writing out XML in Python?

1
  • 2
    For very large XML, an _not_so_elegant_but_working solution is using a template engine (like Cheetah for example: cheetahtemplate.org) Commented Mar 21, 2014 at 8:24

2 Answers 2

1

https://docs.python.org/3/library/xml.sax.handler.html and for an example of Bible in OSIS XML take a look at this script.

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

Comments

0

I don't know of a direct SAX-like way in Python; but I wrote a library for this that might perhaps be useful to you. It provides methods to open and close elements, make pis, comments, doctypes, etc. It has a fair range of higher-level features, like keeping track of what elements and inherited xml:lang values (if any) are in play, doing all the escaping for you (even %xx escaping for URIs in attributes), and things like "closeToElement(type)" etc. I find it makes it much easier to produce WF XML from Python. At http://www.derose.net/steve/utilities/PY/XmlOutput.py if interested.

Comments

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.