【发布时间】:2014-03-21 08:10:56
【问题描述】:
查看Python SAX documentation 我只看到阅读 XML 使用SAX。但我想写它。
我不久前想出了to do that in Java:
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();
}
什么是 Python 等价物?我使用 ElementTree 检查了answer on SO - 但那是 DOM 做事的方式(对于非常大的输出来说是有问题的)。 Another question 未得到答复。或者:用 Python 写出 XML 的更好方法是什么?
【问题讨论】:
-
对于非常大的 XML,_not_so_elegant_but_working 解决方案是使用模板引擎(例如 Cheetah:cheetahtemplate.org)