查看 Python SAX documentation我只看到使用 SAX 来读取 XML。但我想写它。
我想出了如何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 的等价物是什么?我查了一个answer on SO使用 ElementTree - 但这是 DOM 做事的方式(对于非常大的输出来说是有问题的)。 Another question未回答。或者:用 Python 编写 XML 的更好方法是什么?
最佳答案
关于java - 使用 SAX 在 Python 中编写 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22553401/