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.
Writing XML in Python using SAX
题
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?
解决方案
其他提示
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.