import java.io.InputStream;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;

public class InOutStAXStream {

  public static void startParsing(InputStream in, OutputStream out) {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    try {
      XMLStreamReader parser = inputFactory.createXMLStreamReader(in, "UTF-8");
      XMLStreamWriter writer = outputFactory.createXMLStreamWriter(out, "UTF-8");
      writer.writeStartDocument("UTF-8", "1.0");
      writer.writeCharacters("\n");
      boolean goOn = true;
      while (goOn) {
	int event = parser.next();
	switch(event) {
	case XMLStreamConstants.DTD:
	  String doctypedecl = parser.getText();
	  writer.writeDTD(doctypedecl);
	  writer.writeCharacters("\n");
	  break;
	case XMLStreamConstants.END_DOCUMENT:
	  parser.close();
	  writer.flush();
	  writer.close();
	  goOn = false;
	  break;
	case XMLStreamConstants.START_ELEMENT:
	  copyStartElement(parser,writer);
	  break;
	case XMLStreamConstants.CHARACTERS:
	  writer.writeCharacters(parser.getText());
	  break;
	case XMLStreamConstants.END_ELEMENT:
	  writer.writeEndElement();
	}
      }
    } catch (Exception e) { e.printStackTrace(); }
  }

  private static void copyStartElement(XMLStreamReader parser, XMLStreamWriter writer)
      throws XMLStreamException {
    writer.writeStartElement(parser.getLocalName());
    if (parser.getAttributeCount() > 0) {
      int n = parser.getAttributeCount();
      for (int i = 0; i < parser.getAttributeCount(); i++)
        writer.writeAttribute(parser.getAttributeLocalName(i),
                              parser.getAttributeValue(i));
    }
  }
  public static void main(String[] args) {
    try {
      InOutStAXStream.startParsing(new FileInputStream("mondial.xml"), System.out);
    } catch (Exception e) { e.printStackTrace(); }
} }

