Java by API/javax.xml.stream/XMLOutputFactory

Материал из Java эксперт
Перейти к: навигация, поиск

XMLOutputFactory: createXMLEventWriter(OutputStream stream)

  
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.events.XMLEvent;
public class Main {
  public static void main(String[] args) throws Exception {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEventWriter writer = outputFactory.createXMLEventWriter(System.out);
    writer.add(eventFactory.createStartDocument("UTF-8", "1.0"));
    writer.add(eventFactory.createStartElement(new QName("p"), null, null));
    XMLEvent sampleElement = eventFactory.createStartElement("", null, "s", null, null);
    writer.add(sampleElement);
    writer.add(eventFactory.createEndElement("", null, "s"));
    writer.add(sampleElement);
    writer.add(eventFactory.createEndDocument());
    writer.flush();
  }
}





XMLOutputFactory: createXMLStreamWriter(OutputStream stream)

  

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
public class Main {
  public static void main(String[] args) throws Exception {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = outputFactory.createXMLStreamWriter(System.out);
    writer.writeStartDocument("1.0");
    writer.writeCharacters("\n");
    writer.writeStartElement("ns1", "sample", "http://www.e.ru/ns1");
    writer.writeNamespace("ns1", "http://www.e.ru/ns1");
    writer.writeEmptyElement("http://www.e.ru/ns1", "inner1");
    writer.writeAttribute("otherAttribute", "true");
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    System.out.println();
  }
}