Java Tutorial/XML/Stream Parser — различия между версиями

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

Текущая версия на 05:18, 1 июня 2010

Catch XMLStreamException

import java.io.FileInputStream;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;

class StaxCursorTest {
    public static void main(String[] args) throws Exception {
        String filename = "yourXML.xml";
        XMLInputFactory xmlif = null;
        xmlif = XMLInputFactory.newInstance();
        xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,Boolean.TRUE);
        xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,Boolean.FALSE);
        xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
        try {
            XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename,new FileInputStream(filename));
            int eventType = xmlr.getEventType();
            printStartDocument(xmlr);
            while (xmlr.hasNext()) {
                eventType = xmlr.next();
                printStartElement(xmlr);
                printEndElement(xmlr);
                printText(xmlr);
                printPIData(xmlr);
                printComment(xmlr);
            }
        } catch (XMLStreamException ex) {
            System.out.println(ex.getMessage());
            if (ex.getNestedException() != null) {
                ex.getNestedException()
                  .printStackTrace();
            }
        }
    }
    public static final String getEventTypeString(int eventType) {
        switch (eventType) {
        case XMLEvent.START_ELEMENT:
            return "START_ELEMENT";
        case XMLEvent.END_ELEMENT:
            return "END_ELEMENT";
        case XMLEvent.PROCESSING_INSTRUCTION:
            return "PROCESSING_INSTRUCTION";
        case XMLEvent.CHARACTERS:
            return "CHARACTERS";
        case XMLEvent.ruMENT:
            return "COMMENT";
        case XMLEvent.START_DOCUMENT:
            return "START_DOCUMENT";
        case XMLEvent.END_DOCUMENT:
            return "END_DOCUMENT";
        case XMLEvent.ENTITY_REFERENCE:
            return "ENTITY_REFERENCE";
        case XMLEvent.ATTRIBUTE:
            return "ATTRIBUTE";
        case XMLEvent.DTD:
            return "DTD";
        case XMLEvent.CDATA:
            return "CDATA";
        case XMLEvent.SPACE:
            return "SPACE";
        }
        return "UNKNOWN_EVENT_TYPE , " + eventType;
    }
    private static void printEventType(int eventType) {
        System.out.println("EVENT TYPE(" + eventType + ") = " + getEventTypeString(eventType));
    }
    private static void printStartDocument(XMLStreamReader xmlr) {
        if (xmlr.START_DOCUMENT == xmlr.getEventType()) {
            System.out.println(
                    "<?xml version=\"" + xmlr.getVersion() + "\""
                    + " encoding=\"" + xmlr.getCharacterEncodingScheme() + "\""
                    + "?>");
        }
    }
    private static void printComment(XMLStreamReader xmlr) {
        if (xmlr.getEventType() == xmlr.ruMENT) {
            System.out.print("<!--" + xmlr.getText() + "-->");
        }
    }
    private static void printText(XMLStreamReader xmlr) {
        if (xmlr.hasText()) {
            System.out.print(xmlr.getText());
        }
    }
    private static void printPIData(XMLStreamReader xmlr) {
        if (xmlr.getEventType() == XMLEvent.PROCESSING_INSTRUCTION) {
            System.out.print(
                    "<?" + xmlr.getPITarget() + " " + xmlr.getPIData() + "?>");
        }
    }
    private static void printStartElement(XMLStreamReader xmlr) {
        if (xmlr.isStartElement()) {
            System.out.print("<" + xmlr.getName().toString());
            printAttributes(xmlr);
            System.out.print(">");
        }
    }
    private static void printEndElement(XMLStreamReader xmlr) {
        if (xmlr.isEndElement()) {
            System.out.print("</" + xmlr.getName().toString() + ">");
        }
    }
    private static void printAttributes(XMLStreamReader xmlr) {
        int count = xmlr.getAttributeCount();
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                System.out.print(" ");
                System.out.print(xmlr.getAttributeName(i).toString());
                System.out.print("=");
                System.out.print("\"");
                System.out.print(xmlr.getAttributeValue(i));
                System.out.print("\"");
            }
        }
        count = xmlr.getNamespaceCount();
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                System.out.print(" ");
                System.out.print("xmlns");
                if (xmlr.getNamespacePrefix(i) != null) {
                    System.out.print(":" + xmlr.getNamespacePrefix(i));
                }
                System.out.print("=");
                System.out.print("\"");
                System.out.print(xmlr.getNamespaceURI(i));
                System.out.print("\"");
            }
        }
    }
}





Get information as an XMLEvent object when using cursor approach

import java.io.FileInputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.util.XMLEventAllocator;
import com.sun.xml.internal.stream.events.XMLEventAllocatorImpl;

class CursorApproachEventObject {
    static XMLEventAllocator allocator = null;
    public static void main(String[] args) throws Exception {
        String filename = "yourXML.xml";
        XMLInputFactory xmlif = XMLInputFactory.newInstance();
        xmlif.setEventAllocator(new XMLEventAllocatorImpl());
        allocator = xmlif.getEventAllocator();
        XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename,new FileInputStream(filename));
        int eventType = xmlr.getEventType();
        while (xmlr.hasNext()) {
            eventType = xmlr.next();
            if ((eventType == XMLStreamConstants.START_ELEMENT)&& xmlr.getLocalName().equals("Book")) {
                StartElement event = getXMLEvent(xmlr).asStartElement();
                System.out.println("EVENT: " + event.toString());
            }
        }
    }
    private static XMLEvent getXMLEvent(XMLStreamReader reader)
        throws XMLStreamException {
        return allocator.allocate(reader);
    }
}





Read Xml from StreamSource

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
 * Few simple utils to read DOM. This is originally from the Jakarta Commons
 * Modeler.
 * 
 * @author Costin Manolache
 */
public class Utils {
  public static Document readXml(StreamSource is) throws SAXException, IOException,
      ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);
    // dbf.setCoalescing(true);
    // dbf.setExpandEntityReferences(true);
    DocumentBuilder db = null;
    db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    // db.setErrorHandler( new MyErrorHandler());
    InputSource is2 = new InputSource();
    is2.setSystemId(is.getSystemId());
    is2.setByteStream(is.getInputStream());
    is2.setCharacterStream(is.getReader());
    return db.parse(is2);
  }
}
class NullResolver implements EntityResolver {
  public InputSource resolveEntity(String publicId, String systemId) throws SAXException,
      IOException {
    return new InputSource(new StringReader(""));
  }
}





STAX cursor

import java.io.FileInputStream;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;

class StaxCursorTest {
    public static void main(String[] args) throws Exception {
        String filename = "yourXML.xml";
        XMLInputFactory xmlif = null;
        xmlif = XMLInputFactory.newInstance();
        xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,Boolean.TRUE);
        xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,Boolean.FALSE);
        xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
        try {
            XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename,new FileInputStream(filename));
            int eventType = xmlr.getEventType();
            printStartDocument(xmlr);
            while (xmlr.hasNext()) {
                eventType = xmlr.next();
                printStartElement(xmlr);
                printEndElement(xmlr);
                printText(xmlr);
                printPIData(xmlr);
                printComment(xmlr);
            }
        } catch (XMLStreamException ex) {
            System.out.println(ex.getMessage());
            if (ex.getNestedException() != null) {
                ex.getNestedException()
                  .printStackTrace();
            }
        }
    }
    public static final String getEventTypeString(int eventType) {
        switch (eventType) {
        case XMLEvent.START_ELEMENT:
            return "START_ELEMENT";
        case XMLEvent.END_ELEMENT:
            return "END_ELEMENT";
        case XMLEvent.PROCESSING_INSTRUCTION:
            return "PROCESSING_INSTRUCTION";
        case XMLEvent.CHARACTERS:
            return "CHARACTERS";
        case XMLEvent.ruMENT:
            return "COMMENT";
        case XMLEvent.START_DOCUMENT:
            return "START_DOCUMENT";
        case XMLEvent.END_DOCUMENT:
            return "END_DOCUMENT";
        case XMLEvent.ENTITY_REFERENCE:
            return "ENTITY_REFERENCE";
        case XMLEvent.ATTRIBUTE:
            return "ATTRIBUTE";
        case XMLEvent.DTD:
            return "DTD";
        case XMLEvent.CDATA:
            return "CDATA";
        case XMLEvent.SPACE:
            return "SPACE";
        }
        return "UNKNOWN_EVENT_TYPE , " + eventType;
    }
    private static void printEventType(int eventType) {
        System.out.println("EVENT TYPE(" + eventType + ") = " + getEventTypeString(eventType));
    }
    private static void printStartDocument(XMLStreamReader xmlr) {
        if (xmlr.START_DOCUMENT == xmlr.getEventType()) {
            System.out.println(
                    "<?xml version=\"" + xmlr.getVersion() + "\""
                    + " encoding=\"" + xmlr.getCharacterEncodingScheme() + "\""
                    + "?>");
        }
    }
    private static void printComment(XMLStreamReader xmlr) {
        if (xmlr.getEventType() == xmlr.ruMENT) {
            System.out.print("<!--" + xmlr.getText() + "-->");
        }
    }
    private static void printText(XMLStreamReader xmlr) {
        if (xmlr.hasText()) {
            System.out.print(xmlr.getText());
        }
    }
    private static void printPIData(XMLStreamReader xmlr) {
        if (xmlr.getEventType() == XMLEvent.PROCESSING_INSTRUCTION) {
            System.out.print(
                    "<?" + xmlr.getPITarget() + " " + xmlr.getPIData() + "?>");
        }
    }
    private static void printStartElement(XMLStreamReader xmlr) {
        if (xmlr.isStartElement()) {
            System.out.print("<" + xmlr.getName().toString());
            printAttributes(xmlr);
            System.out.print(">");
        }
    }
    private static void printEndElement(XMLStreamReader xmlr) {
        if (xmlr.isEndElement()) {
            System.out.print("</" + xmlr.getName().toString() + ">");
        }
    }
    private static void printAttributes(XMLStreamReader xmlr) {
        int count = xmlr.getAttributeCount();
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                System.out.print(" ");
                System.out.print(xmlr.getAttributeName(i).toString());
                System.out.print("=");
                System.out.print("\"");
                System.out.print(xmlr.getAttributeValue(i));
                System.out.print("\"");
            }
        }
        count = xmlr.getNamespaceCount();
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                System.out.print(" ");
                System.out.print("xmlns");
                if (xmlr.getNamespacePrefix(i) != null) {
                    System.out.print(":" + xmlr.getNamespacePrefix(i));
                }
                System.out.print("=");
                System.out.print("\"");
                System.out.print(xmlr.getNamespaceURI(i));
                System.out.print("\"");
            }
        }
    }
}





StAX is a technology similar to SAX.

StAX is based on a pull technology.

StAX is the client that queries the StAX parser for more elements.

It allows you to iterate over the elements being read, similar to having a ResultSet in a JDBC application.

StAX classes and interfaces are in javax.xml.stream package and its two subpackages, javax.xml.stream.events and javax.xml.stream.util.

The four most prominent interfaces are XMLStreamReader, XMLEventReader, XMLStreamWriter, and XMLEventWriter, all of which are part of javax.xml.stream.



import java.io.FileReader;
import java.io.Reader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
public class XMLStreamReaderDemo {
  public static void main(String[] args) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    Reader fileReader = new FileReader("source.xml");
    XMLStreamReader reader = factory.createXMLStreamReader(fileReader);
    while (reader.hasNext()) {
      process(reader);
      reader.next();
    }
  }
  private static void process(XMLStreamReader reader) {
    int eventType = reader.getEventType();
    switch (eventType) {
    case XMLStreamConstants.START_ELEMENT:
      System.out.println("Start element: " + reader.getLocalName());
      int count = reader.getAttributeCount();
      for (int i = 0; i < count; i++) {
        String name = reader.getAttributeLocalName(i);
        String value = reader.getAttributeValue(i);
        System.out.println("\tAttribute name/value: " + name + "/" + value);
      }
      break;
    case XMLStreamConstants.END_ELEMENT:
      System.out.println("End element: " + reader.getLocalName());
      break;
    case XMLStreamConstants.CHARACTERS:
      System.out.println("Text: " + reader.getText());
      break;
    default:
      break;
    }
  }
}





Stax XML cursor read

import java.io.FileReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
public class STAXCursorRead {
  public static void main(String args[]) throws Exception {
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    XMLStreamReader xmlsr = xmlif.createXMLStreamReader(new FileReader("points.xml"));
    int eventType;
    while (xmlsr.hasNext()) {
      eventType = xmlsr.next();
      switch (eventType) {
      case XMLEvent.START_ELEMENT:
        System.out.println(xmlsr.getName());
        break;
      case XMLEvent.CHARACTERS:
        System.out.println(xmlsr.getText());
        break;
      default:
        break;
      }
    }
  }
}





Stax XML iterator read

import java.io.FileReader;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.XMLEvent;
public class STAXIteratorRead {
  public static void main(String args[]) throws Exception {
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    XMLEventReader xmler = xmlif.createXMLEventReader(new FileReader("yourFile.xml"));
    XMLEvent event;
    while (xmler.hasNext()) {
      event = xmler.nextEvent();
      if (event.isStartElement()) {
        System.out.println(event.asStartElement().getName());
      } else if (event.isCharacters()) {
        System.out.println(event.asCharacters().getData());
      }
    }
  }
}





Streaming XML Parser: Stax Event

import java.io.FileInputStream;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
import javax.xml.namespace.QName;

public class EventParse {
    public static void main(String[] args) throws Exception {
        String filename = "yourXML.xml";
        XMLInputFactory factory = XMLInputFactory.newInstance();
        System.out.println("FACTORY: " + factory);
        XMLEventReader r = factory.createXMLEventReader(filename,new FileInputStream(filename));
        while (r.hasNext()) {
            XMLEvent e = r.nextEvent();
            System.out.println(e.toString());
        }
    }
    public static final String getEventTypeString(int eventType) {
        switch (eventType) {
        case XMLEvent.START_ELEMENT:
            return "START_ELEMENT";
        case XMLEvent.END_ELEMENT:
            return "END_ELEMENT";
        case XMLEvent.PROCESSING_INSTRUCTION:
            return "PROCESSING_INSTRUCTION";
        case XMLEvent.CHARACTERS:
            return "CHARACTERS";
        case XMLEvent.ruMENT:
            return "COMMENT";
        case XMLEvent.START_DOCUMENT:
            return "START_DOCUMENT";
        case XMLEvent.END_DOCUMENT:
            return "END_DOCUMENT";
        case XMLEvent.ENTITY_REFERENCE:
            return "ENTITY_REFERENCE";
        case XMLEvent.ATTRIBUTE:
            return "ATTRIBUTE";
        case XMLEvent.DTD:
            return "DTD";
        case XMLEvent.CDATA:
            return "CDATA";
        case XMLEvent.SPACE:
            return "SPACE";
        }
        return "UNKNOWN_EVENT_TYPE " + "," + eventType;
    }
}





Streaming XML Parser: Stax Event Filter

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
import java.util.Date;
import javax.xml.namespace.QName;

public class MyStreamFilter implements javax.xml.stream.StreamFilter {
    public static void main(String[] args) throws Exception {
        String filename = "yourXML.xml";
        XMLInputFactory xmlif = null;
        xmlif = XMLInputFactory.newInstance();
        xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,Boolean.TRUE);
        xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,Boolean.FALSE);
        xmlif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        System.out.println("FACTORY: " + xmlif);
        System.out.println("filename = " + filename);
        FileInputStream fis = new FileInputStream(filename);
        XMLStreamReader xmlr = xmlif.createFilteredReader(xmlif.createXMLStreamReader(fis),new MyStreamFilter());
        int eventType = xmlr.getEventType();
        printEventType(eventType);
        while (xmlr.hasNext()) {
                eventType = xmlr.next();
                printEventType(eventType);
                printName(xmlr, eventType);
                printText(xmlr);
                if (xmlr.isStartElement()) {
                    printAttributes(xmlr);
                }
                printPIData(xmlr);
        }
    }
    public static final String getEventTypeString(int eventType) {
        switch (eventType) {
        case XMLEvent.START_ELEMENT:
            return "START_ELEMENT";
        case XMLEvent.END_ELEMENT:
            return "END_ELEMENT";
        case XMLEvent.PROCESSING_INSTRUCTION:
            return "PROCESSING_INSTRUCTION";
        case XMLEvent.CHARACTERS:
            return "CHARACTERS";
        case XMLEvent.ruMENT:
            return "COMMENT";
        case XMLEvent.START_DOCUMENT:
            return "START_DOCUMENT";
        case XMLEvent.END_DOCUMENT:
            return "END_DOCUMENT";
        case XMLEvent.ENTITY_REFERENCE:
            return "ENTITY_REFERENCE";
        case XMLEvent.ATTRIBUTE:
            return "ATTRIBUTE";
        case XMLEvent.DTD:
            return "DTD";
        case XMLEvent.CDATA:
            return "CDATA";
        }
        return "UNKNOWN_EVENT_TYPE";
    }
    private static void printEventType(int eventType) {
        System.out.print("EVENT TYPE(" + eventType + "):");
        System.out.println(getEventTypeString(eventType));
    }
    private static void printName(
        XMLStreamReader xmlr,
        int eventType) {
        if (xmlr.hasName()) {
            System.out.println("HAS NAME: " + xmlr.getLocalName());
        } else {
            System.out.println("HAS NO NAME");
        }
    }
    private static void printText(XMLStreamReader xmlr) {
        if (xmlr.hasText()) {
            System.out.println("HAS TEXT: " + xmlr.getText());
        } else {
            System.out.println("HAS NO TEXT");
        }
    }
    private static void printPIData(XMLStreamReader xmlr) {
        if (xmlr.getEventType() == XMLEvent.PROCESSING_INSTRUCTION) {
            System.out.println(" PI target = " + xmlr.getPITarget());
            System.out.println(" PI Data = " + xmlr.getPIData());
        }
    }
    private static void printAttributes(XMLStreamReader xmlr) {
        if (xmlr.getAttributeCount() > 0) {
            System.out.println("\nHAS ATTRIBUTES: ");
            int count = xmlr.getAttributeCount();
            for (int i = 0; i < count; i++) {
                QName name = xmlr.getAttributeName(i);
                String namespace = xmlr.getAttributeNamespace(i);
                String type = xmlr.getAttributeType(i);
                String prefix = xmlr.getAttributePrefix(i);
                String value = xmlr.getAttributeValue(i);
                System.out.println("ATTRIBUTE-PREFIX: " + prefix);
                System.out.println("ATTRIBUTE-NAMESP: " + namespace);
                System.out.println("ATTRIBUTE-NAME:   " + name.toString());
                System.out.println("ATTRIBUTE-VALUE:  " + value);
                System.out.println("ATTRIBUTE-TYPE:  " + type);
            }
        } else {
            System.out.println("HAS NO ATTRIBUTES");
        }
    }
    public boolean accept(XMLStreamReader reader) {
        if (!reader.isStartElement() && !reader.isEndElement()) {
            return false;
        } else {
            return true;
        }
    }
}





Using XMLEventFactory to create xml document

import java.util.Arrays;
import java.util.List;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndDocument;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
public class XMLEventWriterDemo {
  public static void main(String[] args) throws Exception {
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLEventWriter writer = outputFactory.createXMLEventWriter(System.out);
    XMLEventFactory xmlEventFactory = XMLEventFactory.newInstance();
    StartDocument startDocument = xmlEventFactory.createStartDocument("UTF-8", "1.0");
    writer.add(startDocument);
    StartElement startElement = xmlEventFactory.createStartElement("", "", "My-list");
    writer.add(startElement);
    Attribute attribute = xmlEventFactory.createAttribute("version", "1");
    List attributeList = Arrays.asList(attribute);
    List nsList = Arrays.asList();
    StartElement startElement2 = xmlEventFactory.createStartElement("", "", "Item",
        attributeList.iterator(), nsList.iterator());
    writer.add(startElement2);
    StartElement codeSE = xmlEventFactory.createStartElement("", "", "code");
    writer.add(codeSE);
    Characters codeChars = xmlEventFactory.createCharacters("I001");
    writer.add(codeChars);
    EndElement codeEE = xmlEventFactory.createEndElement("", "", "code");
    writer.add(codeEE);
    StartElement nameSE = xmlEventFactory.createStartElement(" ", " ", "name");
    writer.add(nameSE);
    Characters nameChars = xmlEventFactory.createCharacters("a name");
    writer.add(nameChars);
    EndElement nameEE = xmlEventFactory.createEndElement("", "", "name");
    writer.add(nameEE);
    StartElement contactSE = xmlEventFactory.createStartElement("", "", "contact");
    writer.add(contactSE);
    Characters contactChars = xmlEventFactory.createCharacters("another name");
    writer.add(contactChars);
    EndElement contactEE = xmlEventFactory.createEndElement("", "", "contact");
    writer.add(contactEE);
    EndDocument ed = xmlEventFactory.createEndDocument();
    writer.add(ed);
    writer.flush();
    writer.close();
  }
}





Using XMLStreamWriter to create XML file

import java.io.FileWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import java.util.Date;
import javax.xml.namespace.QName;
public class CursorWriter {
    public static void main(String[] args) throws Exception {
        String fileName = "yourXML.xml";
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLStreamWriter xtw = null;
        xtw = xof.createXMLStreamWriter(new FileWriter(fileName));
        xtw.writeComment("all elements here are explicitly in the HTML namespace");
        xtw.writeStartDocument("utf-8", "1.0");
        xtw.setPrefix("html", "http://www.w3.org/TR/REC-html40");
        xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "html");
        xtw.writeNamespace("html", "http://www.w3.org/TR/REC-html40");
        xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "head");
        xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "title");
        xtw.writeCharacters("character");
        xtw.writeEndElement();
        xtw.writeEndElement();
        xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "body");
        xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "p");
        xtw.writeCharacters("another character");
        xtw.writeStartElement("http://www.w3.org/TR/REC-html40", "a");
        xtw.writeAttribute("href", "http://www.jexp.ru");
        xtw.writeCharacters("here");
        xtw.writeEndElement();
        xtw.writeEndElement();
        xtw.writeEndElement();
        xtw.writeEndElement();
        xtw.writeEndDocument();
        xtw.flush();
        xtw.close();
        System.out.println("Done");
    }
}





Validate Stax

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 * 
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 * 
 * Contributor(s):
 * 
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don"t indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */
/*
 * Validate.java
 *
 * Created on May 28, 2005, 3:02 PM
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
/**
 * 
 * @author pv156767
 */
public class ValidateStax {
  /**
   * @param args
   *          the command line arguments
   */
  public static void main(String[] args) {
    try {
      // TODO code application logic here
      SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      System.out.println("schema factory instance obtained is " + sf);
      Schema schema = sf.newSchema(new File(args[0]));
      System.out.println("schema obtained is = " + schema);
      // Get a Validator which can be used to validate instance document against
      // this grammar.
      Validator validator = schema.newValidator();
      // Validate this instance document against the Instance document supplied
      String fileName = args[1].toString();
      String fileName2 = args[2].toString();
      javax.xml.transform.Result xmlResult = new javax.xml.transform.stax.StAXResult(
          XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(fileName2)));
      javax.xml.transform.Source xmlSource = new javax.xml.transform.stax.StAXSource(
          getXMLEventReader(fileName));
      // validator.validate(new StreamSource(args[1]));
      validator.validate(xmlSource, xmlResult);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.out.println("GET CAUSE");
      ex.getCause().fillInStackTrace();
    }
  }
  private static XMLEventReader getXMLEventReader(String filename) {
    XMLInputFactory xmlif = null;
    XMLEventReader xmlr = null;
    try {
      xmlif = XMLInputFactory.newInstance();
      xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
      xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
      xmlif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
      xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
      FileInputStream fis = new FileInputStream(filename);
      xmlr = xmlif.createXMLEventReader(filename, fis);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return xmlr;
  }
}





XMLEventReader and XMLEventWriter for Stax XML parser

import java.util.Calendar;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.XMLEvent;

class StaxEvent {
    XMLEventFactory m_eventFactory = XMLEventFactory.newInstance();
    public static void main(String[] args) throws Exception {
            StaxEvent ms = new StaxEvent();
            XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(new java.io.FileInputStream("yourXML.xml"));
            XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(System.out);
            while (reader.hasNext()) {
                XMLEvent event = (XMLEvent) reader.next();
                if (event.getEventType() == event.CHARACTERS) {
                    writer.add(ms.getNewCharactersEvent(event.asCharacters()));
                } else {
                    writer.add(event);
                }
            }
            writer.flush();
    }
    private Characters getNewCharactersEvent(Characters event) {
        if (event.getData().equalsIgnoreCase("Name1")) {
            return m_eventFactory.createCharacters(Calendar.getInstance().getTime().toString());
        } else {
            return event;
        }
    }
}





XMLEventReader Demo

import java.io.FileReader;
import java.io.Reader;
import java.util.Iterator;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
public class XMLEventReaderDemo {
  public static void main(String[] args) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    Reader fileReader = new FileReader("Source.xml");
    XMLEventReader reader = factory.createXMLEventReader(fileReader);
    while (reader.hasNext()) {
      XMLEvent event = reader.nextEvent();
      if (event.isStartElement()) {
        StartElement element = (StartElement) event;
        System.out.println("Start Element: " + element.getName());
        Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
          Attribute attribute = (Attribute) iterator.next();
          QName name = attribute.getName();
          String value = attribute.getValue();
          System.out.println("Attribute name/value: " + name + "/" + value);
        }
      }
      if (event.isEndElement()) {
        EndElement element = (EndElement) event;
        System.out.println("End element:" + element.getName());
      }
      if (event.isCharacters()) {
        Characters characters = (Characters) event;
        System.out.println("Text: " + characters.getData());
      }
    }
  }
}





XMLStreamWriter Demo

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
public class XMLStreamWriterDemo {
  public static void main(String[] args) throws Exception {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = factory.createXMLStreamWriter(System.out);
    writer.writeStartDocument("1.0");
    writer.writeStartElement("catalog");
    writer.writeStartElement("book");
    writer.writeAttribute("id", "1");
    writer.writeStartElement("code");
    writer.writeCharacters("I01");
    writer.writeEndElement();
    writer.writeStartElement("title");
    writer.writeCharacters("This is the title");
    writer.writeEndElement();
    writer.writeStartElement("price");
    writer.writeCharacters("$2.95");
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();
  }
}