• xml


    package com.matt.xml.sax;

    import lombok.extern.slf4j.Slf4j;
    import org.junit.Test;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.AttributesImpl;

    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Result;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamResult;
    import java.io.StringWriter;

    @Slf4j
    public class SaxXml {

    @Test
    public void test01() {

    StringWriter writer = new StringWriter();
    Result resultStr = new StreamResult(writer);
    SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    try {
    TransformerHandler handler = saxTransformerFactory.newTransformerHandler();
    Transformer tr = handler.getTransformer();
    tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    tr.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(resultStr);
    handler.startDocument();
    AttributesImpl attr = new AttributesImpl();
    handler.startElement("", "", "bookstore", attr);
    attr.clear();

    attr.addAttribute("http:\localhost:8090:rem\233", "test", "id", "", "2233");
    handler.startElement("", "", "book", attr);

    attr.clear();
    handler.startElement("http:\\localhost:8090:rem\233", "test", "name", attr);
    String bookName = "羊皮卷";
    handler.characters(bookName.toCharArray(), 0, bookName.length());
    handler.endElement("http:\\localhost:8090:rem\233", "test", "name");

    attr.clear();
    String bookYear = "1986";
    handler.startElement("", "", "year", attr);
    handler.characters(bookYear.toCharArray(), 0, bookYear.length());
    handler.endElement("", "", "year");

    handler.endElement("", "", "book");
    handler.endElement("", "", "bookstore");

    handler.endDocument();

    log.info("{}", resultStr);

    log.info("{}", writer.toString());

    } catch (TransformerConfigurationException e) {
    e.printStackTrace();
    } catch (SAXException e) {

    }

    }
    }
  • 相关阅读:
    【后缀数组】poj2406 Power Strings
    [HNOI 2013]游走
    [HAOI 2008]木棍分割
    [SCOI 2010]传送带
    [SDOI 2010]魔法猪学院
    [Codeforces 235B]Let's Play Osu!
    [SPOJ 10628]Count on a tree
    [ZJOI 2010]count 数字计数
    [SHOI 2008]Debt 循环的债务
    [JSOI 2008]星球大战starwar
  • 原文地址:https://www.cnblogs.com/zhongchang/p/14969981.html
Copyright © 2020-2023  润新知