代码之家  ›  专栏  ›  技术社区  ›  Grant Wagner

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

  •  2
  • Grant Wagner  · 技术社区  · 16 年前

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

    2 回复  |  直到 15 年前
        1
  •  4
  •   Grant Wagner    16 年前

    不,这不是真的,你可以用类似于

    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();
    
        2
  •  0
  •   Tom Hawtin - tackline    16 年前

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