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) {
}
}
}