List of usage examples for javax.xml.stream XMLStreamReader hasNext
public boolean hasNext() throws XMLStreamException;
From source file:Main.java
public static void skipToEndElement(XMLStreamReader xmlRdr) throws XMLStreamException { do {//from w w w.ja v a 2s.c o m if (xmlRdr.getEventType() == XMLStreamConstants.END_ELEMENT) { break; } xmlRdr.next(); } while (xmlRdr.hasNext()); }
From source file:Main.java
/** * Skip current element, including all its content. * Precondition: the current event is START_ELEMENT. * Postcondition: the current event is the corresponding END_ELEMENT. * Similar to {@link XMLStreamReader#nextTag()}, but also skips text content. * @param reader must not be {@code null} * @throws XMLStreamException if the current event is not START_ELEMENT or there is an error processing the underlying XML source */// ww w .j av a2 s . c o m public static void skipElement(XMLStreamReader reader) throws XMLStreamException { if (reader.getEventType() != START_ELEMENT) throw new XMLStreamException("expected start of element", reader.getLocation()); int depth = 0; while (reader.hasNext()) { int event = reader.next(); if (event == START_ELEMENT) { ++depth; } else if (event == END_ELEMENT) { --depth; if (depth == -1) break; } } }
From source file:gdv.xport.util.AbstractFormatterTest.java
/** * We use the XMLStreams to validate the XML. * * @param xmlString XML-String//w w w . j a va 2s.c o m * @throws XMLStreamException * the given XML string is not a valid XML */ protected static void checkXML(final String xmlString) throws XMLStreamException { XMLStreamReader xmlr = xmlInputFactory.createXMLStreamReader(new StringReader(xmlString)); int n = 0; while (xmlr.hasNext()) { int eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { n += xmlr.getText().length(); } } log.info(n + " bytes text in " + xmlString.length() + " bytes XML"); }
From source file:Main.java
/** * Moves the parser to the next start element. * //from www.j ava2 s.c o m * @return {@code true} if another start element has been found, * {@code false} otherwise */ public static boolean findNextStartElemenet(XMLStreamReader parser) throws XMLStreamException { assert parser != null; while (true) { int event = parser.getEventType(); if (event == XMLStreamConstants.START_ELEMENT) { return true; } if (parser.hasNext()) { parser.next(); } else { return false; } } }
From source file:net.di2e.ecdr.libs.result.relevance.TextParser.java
/** * Given xml as a string, this method will parse out element text and CDATA text. It separates * each by one space character.//from w w w . ja v a 2s.c o m * * @param xmlData * XML as a {@code String} * @return parsed CDATA and element text */ protected static String parseTextFrom(String xmlData) { StringBuilder builder = new StringBuilder(); XMLStreamReader xmlStreamReader; try { // xml parser does not handle leading whitespace xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(xmlData)); while (xmlStreamReader.hasNext()) { int event = xmlStreamReader.next(); if (event == XMLStreamConstants.CHARACTERS || event == XMLStreamConstants.CDATA) { String text = xmlStreamReader.getText(); if (StringUtils.isNotBlank(text)) { builder.append(" " + text.trim()); } } if (event == XMLStreamConstants.START_ELEMENT) { for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) { String text = xmlStreamReader.getAttributeValue(i); if (StringUtils.isNotBlank(text)) { builder.append(" " + text.trim()); } } } } } catch (XMLStreamException e1) { LOGGER.warn("Failure occurred in parsing the xml data (" + xmlData + "). No data has been stored or indexed.", e1); } return builder.toString(); }
From source file:Main.java
public static String parse(XMLStreamReader reader) { StringBuffer result = new StringBuffer(); if (reader != null) { try {/*w w w.j av a2 s . co m*/ while (reader.hasNext()) { switch (reader.getEventType()) { case XMLStreamConstants.START_ELEMENT: result.append("<"); printName(reader, result); printNamespaces(reader, result); printAttributes(reader, result); result.append(">"); break; case XMLStreamConstants.END_ELEMENT: result.append("</"); printName(reader, result); result.append(">"); break; case XMLStreamConstants.SPACE: case XMLStreamConstants.CHARACTERS: int start = reader.getTextStart(); int length = reader.getTextLength(); result.append(new String(reader.getTextCharacters(), start, length)); break; case XMLStreamConstants.PROCESSING_INSTRUCTION: result.append("<?"); if (reader.hasText()) result.append(reader.getText()); result.append("?>"); break; case XMLStreamConstants.CDATA: result.append("<![CDATA["); start = reader.getTextStart(); length = reader.getTextLength(); result.append(new String(reader.getTextCharacters(), start, length)); result.append("]]>"); break; case XMLStreamConstants.COMMENT: result.append("<!--"); if (reader.hasText()) result.append(reader.getText()); result.append("-->"); break; case XMLStreamConstants.ENTITY_REFERENCE: result.append(reader.getLocalName()).append("="); if (reader.hasText()) result.append("[").append(reader.getText()).append("]"); break; case XMLStreamConstants.START_DOCUMENT: result.append("<?xml"); result.append(" version='").append(reader.getVersion()).append("'"); result.append(" encoding='").append(reader.getCharacterEncodingScheme()).append("'"); if (reader.isStandalone()) result.append(" standalone='yes'"); else result.append(" standalone='no'"); result.append("?>"); break; } reader.next(); } // end while } catch (XMLStreamException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (XMLStreamException e) { } } } return result.toString(); }
From source file:fr.inria.oak.paxquery.pact.operators.unary.NavigationOperator.java
/** * //from w w w . ja v a 2 s.co m * @param record * @param treePattern * @param collector */ public static void navigation(NestedMetadata inputRecordSignature, Record record, int column, NavigationTreePattern navigationTreePattern, Collector<Record> collector) { XMLInputFactory factory = XMLInputFactory.newInstance(); try { StringValue value = record.getField(column, StringValue.class); XMLStreamReader streamReader = factory.createXMLStreamReader(new StringReader(value.getValue())); SingleDocumentExtractor extractor = new SingleDocumentExtractor(navigationTreePattern, streamReader); while (streamReader.hasNext()) { streamReader.next(); if (streamReader.getEventType() == XMLStreamConstants.START_ELEMENT) { extractor.startElement(); } else if (streamReader.getEventType() == XMLStreamConstants.END_ELEMENT) { extractor.endElement(); } else if (streamReader.getEventType() == XMLStreamConstants.CHARACTERS) { extractor.characters(); } if (extractor.getRecords().size() != 0) { Iterator<Record> pactRecordsIterator = extractor.getRecords().iterator(); while (pactRecordsIterator.hasNext()) { Record originalRecord = record.createCopy(); RecordOperations.concatenate(originalRecord, pactRecordsIterator.next()); collector.collect(originalRecord); } extractor.getRecords().clear(); } } } catch (XMLStreamException e) { logger.error("XMLStreamException", e); } }
From source file:Main.java
/** * Advance the reader to the next element after start element and return true. * Return false if next start element is not found * @param reader a XMLStreamReader//from ww w .j av a 2s . com * @param startElement Name of the start element. * @return True when successfully advanced the reader. * @throws XMLStreamException Exception when reading from the XMLStreamReader fails. */ public static boolean advanceToAfterStartElement(XMLStreamReader reader, String startElement) throws XMLStreamException { while (!(reader.getEventType() == XMLStreamConstants.START_ELEMENT && reader.hasName() && reader.getLocalName().equalsIgnoreCase(startElement))) { //String name = (reader.hasName()? reader.getLocalName() : ""); if (reader.hasNext()) { reader.next(); } else { // reach the end of elements in reader. Not found. return false; } } // found the startElement. Consume that start element also if (reader.hasNext()) { reader.next(); return true; } return false; }
From source file:com.rockhoppertech.music.midi.js.xml.ModeFactoryXMLHelper.java
/** * Read modes.xml and create {@code Scale instances} from those definitions. *///from ww w . j a v a2 s . co m public static void init() { List<Integer> intervals = null; Scale currentMode = null; String tagContent = null; XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = null; try { reader = factory.createXMLStreamReader(ClassLoader.getSystemResourceAsStream("modes.xml")); } catch (XMLStreamException e) { e.printStackTrace(); return; } try { while (reader.hasNext()) { int event = reader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: String el = reader.getLocalName(); logger.debug("start element '{}'", el); if ("mode".equals(el)) { currentMode = new Scale(); intervals = new ArrayList<>(); } if ("modes".equals(el)) { modeList = new ArrayList<>(); } break; case XMLStreamConstants.CHARACTERS: tagContent = reader.getText().trim(); logger.debug("tagcontent '{}'", tagContent); break; case XMLStreamConstants.END_ELEMENT: switch (reader.getLocalName()) { case "mode": // wow. both guava and commmons to get an int[] array Integer[] array = FluentIterable.from(intervals).toArray(Integer.class); // same as Integer[] array = intervals.toArray(new // Integer[intervals.size()]); int[] a = ArrayUtils.toPrimitive(array); currentMode.setIntervals(a); modeList.add(currentMode); ScaleFactory.registerScale(currentMode); break; case "interval": logger.debug("interval '{}'", tagContent); logger.debug("intervals '{}'", intervals); intervals.add(Integer.parseInt(tagContent)); break; case "name": currentMode.setName(tagContent); break; } break; case XMLStreamConstants.START_DOCUMENT: modeList = new ArrayList<>(); intervals = new ArrayList<>(); break; } } } catch (XMLStreamException e) { logger.error(e.getLocalizedMessage(), e); e.printStackTrace(); } logger.debug("mode list \n{}", modeList); }
From source file:io.cloudslang.content.xml.utils.XmlUtils.java
/** * Returns the Namespaces context from an xml. * * @param xmlString xml as string/* ww w .jav a 2 s .c o m*/ * @param xmlFilePath path to xml file * @return the Namespaces context from an xml. * @throws IOException file reading exception * @throws XMLStreamException parsing exception */ public static NamespaceContext getNamespaceContext(String xmlString, String xmlFilePath) throws Exception { InputStream inputXML = getStream(xmlString, xmlFilePath); XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader reader = inputFactory.createXMLStreamReader(inputXML); Map<String, String> namespaces = new HashMap<>(); while (reader.hasNext()) { int evt = reader.next(); if (evt == XMLStreamConstants.START_ELEMENT) { QName qName = reader.getName(); if (qName != null) { if (qName.getPrefix() != null && qName.getPrefix().compareTo("") != 0) namespaces.put(qName.getPrefix(), qName.getNamespaceURI()); } } } return new SimpleNamespaceContext(namespaces); }