Here you can find the source of getElements(final String elementName, final InputStream is, final boolean onlyValues)
Parameter | Description |
---|---|
elementName | a parameter |
is | a parameter |
onlyValues | a parameter |
Parameter | Description |
---|---|
XMLStreamException | an exception |
UnsupportedEncodingException | an exception |
private static Collection<String> getElements(final String elementName, final InputStream is, final boolean onlyValues) throws XMLStreamException, UnsupportedEncodingException
//package com.java2s; /******************************************************************************* * Manchester Institute of Biotechnology * University of Manchester//from ww w.jav a2 s. co m * Manchester M1 7ND * United Kingdom * * Copyright (C) 2013 University of Manchester * * This program is released under the Academic Free License ("AFL") v3.0. * (http://www.opensource.org/licenses/academic.php) *******************************************************************************/ import java.io.*; import java.nio.charset.*; import java.util.*; import javax.xml.stream.*; import javax.xml.stream.events.*; public class Main { /** * * @param elementName * @param is * @param onlyValues * @return Collection * @throws XMLStreamException * @throws UnsupportedEncodingException */ private 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; } }