如何使用Java 1.4和SAX将任意数据编码为XML?

时间:2008-09-16 15:19:30

标签: java xml sax

我们使用SAX来解析XML,因为它不需要将整个XML文档读入内存以解析单个值。我读过许多文章,坚持认为SAX只能用于解析/解码XML而不能创建它。这是真的吗?

2 个答案:

答案 0 :(得分:4)

不,事实并非如此,您可以使用类似于以下内容的方式将XML编码为Java中的任何Writer:

char[] ch;
AttributesImpl atts = new AttributesImpl();
Writer writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();

// SAX2.0 ContentHandler
TransformerHandler transformerHandler = tf.newTransformerHandler();

Transformer serializer = transformerHandler.getTransformer();

serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "nodes.dtd");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");

transformerHandler.setResult(streamResult);

transformerHandler.startDocument();

atts.clear();
// atts.addAttribute("", "", "xmlns", "CDATA", "http://www.example.com/nodes");
// atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
// atts.addAttribute("", "", "xsi:schemaLocation", "CDATA", "/nodes.xsd");
transformerHandler.startElement("", "", "node_list", atts);

// displayName element
if (displayName != null) {
    transformerHandler.startElement("", "", "display_name", null);
    ch = displayName.toCharArray();
    transformerHandler.characters(ch, 0, ch.length);
    transformerHandler.endElement("", "", "display_name");
}

// nodes element
transformerHandler.startElement("", "", "nodes", null);

atts.clear();
atts.addAttribute("", "", "node_type", "CDATA", "sometype");
transformerHandler.startElement("", "", "node", atts);

ch = node.getValue().toCharArray();
transformerHandler.startElement("", "", "value", null);
transformerHandler.characters(ch, 0, ch.length);
transformerHandler.endElement("", "", "value");

transformerHandler.endElement("", "", "node");

transformerHandler.endElement("", "", "nodes");

transformerHandler.endElement("", "", "node_list");

transformerHandler.endDocument();

String xml = writer.toString();

答案 1 :(得分:0)

SAX处理程序接口设计易于实现。编写一个类似的类(可能包装一个SAX接口)很容易调用 - 链接,记住要关闭的元素,更容易的属性等。