Example usage for javax.xml.stream XMLEventReader next

List of usage examples for javax.xml.stream XMLEventReader next

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventReader next.

Prototype

E next();

Source Link

Document

Returns the next element in the iteration.

Usage

From source file:StaxEvent.java

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 {/*  w  w w  .jav a  2 s  .c o m*/
            writer.add(event);
        }
    }
    writer.flush();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();

    XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream("input.xml"));
    InterestingElementFilter filter = new InterestingElementFilter();
    XMLEventReader interestingElementReader = xmlInputFactory.createFilteredReader(xmlEventReader, filter);

    while (interestingElementReader.hasNext()) {
        XMLEvent xmlEvent = interestingElementReader.peek();
        if (xmlEvent.isStartElement()) {
            System.out.println(xmlEvent.asStartElement().getName());
        }/*  w  w  w  .  j a v  a 2 s  . c o  m*/
        interestingElementReader.next();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader reader = inputFactory.createXMLEventReader(new FileInputStream(new File("a.xml")));
    reader = inputFactory.createFilteredReader(reader, new EventFilter() {
        public boolean accept(XMLEvent event) {
            return false;
        }//from  w  w w.j  av a 2s  . c  o  m
    });
    reader = inputFactory.createFilteredReader(reader, new ElementOnlyFilter());

    System.out.println(reader.hasNext());
    System.out.println(reader.next());
}

From source file:EventFilterExample.java

private static int countEvents(XMLEventReader reader) throws XMLStreamException {
    int counter = 0;
    while (reader.hasNext()) {
        reader.next();
        counter++;/*from  w ww.j  a  v a2 s . c  o m*/
    }
    return counter;
}

From source file:Main.java

/**
 * Returns the name of the root element of an XML message.
 * /*w  ww  . j  av a 2  s.c  o m*/
 * @param xml     XML message
 * @return the name of the root element
 * @exception Exception if an error occurs
 */
public static String getRootElementName(byte[] xml) throws Exception {

    ByteArrayInputStream is = new ByteArrayInputStream(xml);
    XMLEventReader reader = inputFactory.createXMLEventReader(is);

    while (reader.hasNext()) {
        XMLEvent event = (XMLEvent) reader.next();

        if (event.isStartElement()) {
            StartElement startElement = event.asStartElement();
            return startElement.getName().getLocalPart();
        }
    }

    reader.close();
    return "";
}

From source file:com.predic8.membrane.core.util.TextUtil.java

/**
 * Checks whether s is a valid (well-formed and balanced) XML snippet.
 *
 * Note that attributes escaped by single quotes are accepted (which is illegal by spec).
 *///from  www. ja v  a 2  s  .c  o  m
public static boolean isValidXMLSnippet(String s) {
    try {
        XMLEventReader parser;
        synchronized (xmlInputFactory) {
            parser = xmlInputFactory.createXMLEventReader(new StringReader("<a>" + s + "</a>"));
        }
        XMLEvent event = null;
        while (parser.hasNext()) {
            event = (XMLEvent) parser.next();
        }
        return event != null && event.isEndDocument();
    } catch (Exception e) {
        log.error("", e);
        return false;
    }
}

From source file:Main.java

/**
 * //w w w  .  j  a v a2 s  .  c  om
 * @param elementName
 * @param attributeValue
 * @param is
 * @return Collection
 * @throws XMLStreamException
 * @throws FactoryConfigurationError
 * @throws UnsupportedEncodingException
 */
public static Collection<String> getElementValues(final String elementName, final String attributeValue,
        final InputStream is)
        throws XMLStreamException, UnsupportedEncodingException, FactoryConfigurationError {
    final Collection<String> elementValues = new ArrayList<>();
    final XMLEventReader xmlEventReader = XMLInputFactory.newInstance()
            .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name()));
    final StringBuffer characters = new StringBuffer();
    boolean read = false;

    while (xmlEventReader.peek() != null) {
        final XMLEvent event = (XMLEvent) xmlEventReader.next();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.END_DOCUMENT: {
            // Ignore.
            break;
        }
        case XMLStreamConstants.START_ELEMENT: {
            read = elementName.equals(event.asStartElement().getName().getLocalPart());

            if (read && attributeValue != null) {
                read = false;

                for (Iterator<Attribute> iterator = event.asStartElement().getAttributes(); iterator
                        .hasNext();) {
                    Attribute attribute = iterator.next();

                    if (attribute.getValue().equals(attributeValue)) {
                        read = true;
                        break;
                    }
                }
            }

            break;
        }
        case XMLStreamConstants.CHARACTERS: {
            if (read) {
                characters.append(event.asCharacters().getData());
            }
            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (read) {
                elementValues.add(characters.toString());
                characters.setLength(0);
            }

            read = false;
            break;
        }
        default: {
            // Ignore
            break;
        }
        }
    }

    return elementValues;
}

From source file:Main.java

/**
 * /*w w  w. j  a  va  2s.co m*/
 * @param is
 * @param os
 * @param elementNames
 * @throws XMLStreamException
 * @throws FactoryConfigurationError
 * @throws UnsupportedEncodingException
 */
public static void stripElements(final InputStream is, final OutputStream os,
        final Collection<String> elementNames)
        throws XMLStreamException, UnsupportedEncodingException, FactoryConfigurationError {
    final XMLEventReader xmlEventReader = XMLInputFactory.newInstance()
            .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name()));
    final XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(os);

    String elementName = null;

    while (xmlEventReader.peek() != null) {
        final XMLEvent event = (XMLEvent) xmlEventReader.next();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.END_DOCUMENT: {
            // Ignore.
            break;
        }
        case XMLStreamConstants.START_ELEMENT: {
            final StartElement startElement = event.asStartElement();
            final QName name = startElement.getName();

            if (elementNames.contains(name.getLocalPart())) {
                elementName = name.getLocalPart();
            }

            if (elementName == null) {
                xmlEventWriter.add(event);
            }

            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            final EndElement endElement = event.asEndElement();
            final QName name = endElement.getName();

            if (elementName == null) {
                xmlEventWriter.add(event);
            } else if (elementName.equals(name.getLocalPart())) {
                elementName = null;
            }

            break;
        }
        default: {
            if (elementName == null) {
                xmlEventWriter.add(event);
            }
        }
        }
    }

    xmlEventWriter.flush();
}

From source file:Main.java

/**
 * /* w w w . j a  v a  2 s.  co  m*/
 * @param elementName
 * @param is
 * @param onlyValues
 * @return Collection
 * @throws XMLStreamException
 * @throws UnsupportedEncodingException
 */
public static Collection<String> getElements(final String elementName, final InputStream is,
        final boolean onlyValues) throws XMLStreamException, UnsupportedEncodingException {
    final Collection<String> elements = new ArrayList<>();
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    final XMLEventReader reader = XMLInputFactory.newInstance()
            .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name()));
    final XMLEventWriter writer = XMLOutputFactory.newInstance()
            .createXMLEventWriter(new OutputStreamWriter(os, Charset.defaultCharset().name()));
    boolean read = false;
    String characters = null;

    while (reader.peek() != null) {
        final XMLEvent event = (XMLEvent) reader.next();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.END_DOCUMENT: {
            // Ignore.
            break;
        }
        case XMLStreamConstants.START_ELEMENT: {
            read = read || elementName.equals(event.asStartElement().getName().getLocalPart());

            if (read && !onlyValues) {
                writer.add(event);
            }

            break;
        }
        case XMLStreamConstants.ATTRIBUTE: {
            if (read && !onlyValues) {
                writer.add(event);
            }
            break;
        }
        case XMLStreamConstants.CHARACTERS: {
            if (read && !onlyValues) {
                writer.add(event);
            }
            characters = event.asCharacters().getData();
            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (read && !onlyValues) {
                writer.add(event);
            }
            if (elementName.equals(event.asEndElement().getName().getLocalPart())) {
                writer.flush();

                if (characters != null) {
                    elements.add(characters);
                }

                os.reset();
                read = false;
            }
            break;
        }
        default: {
            // Ignore
            break;
        }
        }
    }

    return elements;
}

From source file:org.lieuofs.geo.territoire.biz.dao.EtatTerritoireFichierXmlDao.java

/**************************************************/

@PostConstruct/*from  w w  w .  j  a  v  a  2  s. com*/
public void chargerResource()
        throws IOException, XMLStreamException, FactoryConfigurationError, ParseException {
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(fichier.getInputStream(),
            this.charsetName);
    EtatTerritoirePersistant etatTerritoire = null;
    while (reader.hasNext()) {
        XMLEvent event = (XMLEvent) reader.next();
        if (event.isStartElement()) {
            StartElement element = (StartElement) event;
            String nomElem = element.getName().toString();
            if ("country".equals(nomElem)) {
                etatTerritoire = new EtatTerritoirePersistant();
            } else if ("id".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumeroOFS(Integer.parseInt(characters.getData()));
            } else if ("unId".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                if (null == etatTerritoire.getInfosISO())
                    etatTerritoire.setInfosISO(new InfosONUetISO3166());
                etatTerritoire.getInfosISO().setCodeNumeriqueONU(Integer.parseInt(characters.getData()));
            } else if ("iso2Id".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                if (null == etatTerritoire.getInfosISO())
                    etatTerritoire.setInfosISO(new InfosONUetISO3166());
                etatTerritoire.getInfosISO().setCodeIsoAlpha2(characters.getData());
            } else if ("iso3Id".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                if (null == etatTerritoire.getInfosISO())
                    etatTerritoire.setInfosISO(new InfosONUetISO3166());
                etatTerritoire.getInfosISO().setCodeIsoAlpha3(characters.getData());
            } else if ("shortNameDe".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("de", characters.getData());
            } else if ("shortNameFr".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("fr", characters.getData());
            } else if ("shortNameIt".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("it", characters.getData());
            } else if ("shortNameEn".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterFormeCourte("en", characters.getData());
            } else if ("officialNameDe".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterDesignationOfficielle("de", characters.getData());
            } else if ("officialNameFr".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterDesignationOfficielle("fr", characters.getData());
            } else if ("officialNameIt".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterDesignationOfficielle("it", characters.getData());
            } else if ("continent".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumContinent(Integer.parseInt(characters.getData()));
            } else if ("region".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumRegion(Integer.parseInt(characters.getData()));
            } else if ("state".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setEtat(Boolean.valueOf(characters.getData()));
            } else if ("areaState".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setNumEtatRattachement(Integer.parseInt(characters.getData()));
            } else if ("unMember".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setMembreONU(Boolean.valueOf(characters.getData()));
            } else if ("unEntryDate".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setDateEntreeONU(dateFmt.parse(characters.getData()));
            } else if ("recognizedCh".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setReconnuSuisse(Boolean.valueOf(characters.getData()));
            } else if ("recognizedDate".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setDateReconnaissance(dateFmt.parse(characters.getData()));
            } else if ("remarkDe".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterRemarque("de", characters.getData());
            } else if ("remarkFr".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterRemarque("fr", characters.getData());
            } else if ("remarkIt".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.ajouterRemarque("it", characters.getData());
            } else if ("entryValid".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setValide(Boolean.valueOf(characters.getData()));
            } else if ("dateOfChange".equals(nomElem)) {
                Characters characters = (Characters) reader.next();
                etatTerritoire.setDateDernierChangement(dateFmt.parse(characters.getData()));
            }
        } else if (event.isEndElement()) {
            EndElement element = (EndElement) event;
            if ("country".equals(element.getName().toString())) {
                stockerEtatTerritoire(etatTerritoire);
            }
        }
    }
}