List of usage examples for javax.xml.stream XMLStreamConstants ATTRIBUTE
int ATTRIBUTE
To view the source code for javax.xml.stream XMLStreamConstants ATTRIBUTE.
Click Source Link
From source file:Main.java
/** Get the human readable event name for the numeric event id */ public static String getEventName(int eventId) { switch (eventId) { case XMLStreamConstants.START_ELEMENT: return "StartElementEvent"; case XMLStreamConstants.END_ELEMENT: return "EndElementEvent"; case XMLStreamConstants.PROCESSING_INSTRUCTION: return "ProcessingInstructionEvent"; case XMLStreamConstants.CHARACTERS: return "CharacterEvent"; case XMLStreamConstants.COMMENT: return "CommentEvent"; case XMLStreamConstants.START_DOCUMENT: return "StartDocumentEvent"; case XMLStreamConstants.END_DOCUMENT: return "EndDocumentEvent"; case XMLStreamConstants.ENTITY_REFERENCE: return "EntityReferenceEvent"; case XMLStreamConstants.ATTRIBUTE: return "AttributeBase"; case XMLStreamConstants.DTD: return "DTDEvent"; case XMLStreamConstants.CDATA: return "CDATA"; }//from ww w .java 2 s . co m return "UNKNOWN_EVENT_TYPE"; }
From source file:Main.java
/** * // w ww . ja va 2s.com * @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:com.widowcrawler.exo.parse.Parser.java
private static String getEventTypeString(int eventType) { switch (eventType) { case XMLStreamConstants.START_ELEMENT: return "START_ELEMENT"; case XMLStreamConstants.END_ELEMENT: return "END_ELEMENT"; case XMLStreamConstants.PROCESSING_INSTRUCTION: return "PROCESSING_INSTRUCTION"; case XMLStreamConstants.CHARACTERS: return "CHARACTERS"; case XMLStreamConstants.COMMENT: return "COMMENT"; case XMLStreamConstants.START_DOCUMENT: return "START_DOCUMENT"; case XMLStreamConstants.END_DOCUMENT: return "END_DOCUMENT"; case XMLStreamConstants.ENTITY_REFERENCE: return "ENTITY_REFERENCE"; case XMLStreamConstants.ATTRIBUTE: return "ATTRIBUTE"; case XMLStreamConstants.DTD: return "DTD"; case XMLStreamConstants.CDATA: return "CDATA"; case XMLStreamConstants.SPACE: return "SPACE"; case XMLStreamConstants.ENTITY_DECLARATION: return "ENTITY_DECLARATION"; case XMLStreamConstants.NAMESPACE: return "NAMESPACE"; case XMLStreamConstants.NOTATION_DECLARATION: return "NOTATION_DECLARATION"; }/* w ww. j a v a 2 s .co m*/ return "UNKNOWN_EVENT_TYPE: " + eventType; }
From source file:org.javelin.sws.ext.bind.internal.model.ComplexTypePattern.java
@Override public T consumeValue(XMLEventReader eventReader, UnmarshallingContext context) throws XMLStreamException { // first create an object to be filled (using PropertyAccessors - direct or bean) according to the content model T object = BeanUtils.instantiate(this.getJavaType()); // the order is dictated by incoming events, not by the mode // TODO: create a property to enable strict unmarshalling - dictated by content model // only this (ContentModel) pattern iterates over XML Events XMLEvent event = null;/*from ww w . j a v a2 s . c o m*/ PropertyMetadataValue<T, ?> pmv = null; // this loop will only handle first level of start elements and only single end element // deeper levels will be handled by nested patterns while (true) { boolean end = false; event = eventReader.peek(); pmv = null; switch (event.getEventType()) { case XMLStreamConstants.ATTRIBUTE: pmv = this.consumeNestedAttribute(eventReader, context); break; case XMLStreamConstants.CDATA: case XMLStreamConstants.CHARACTERS: // TODO: XMLEvent.ENTITY_REFERENCE? if (this.simpleContent != null) { pmv = this.consumeSimpleContent(eventReader, context); break; } case XMLStreamConstants.COMMENT: case XMLStreamConstants.DTD: case XMLStreamConstants.SPACE: case XMLStreamConstants.ENTITY_DECLARATION: case XMLStreamConstants.NOTATION_DECLARATION: case XMLStreamConstants.PROCESSING_INSTRUCTION: eventReader.nextEvent(); break; case XMLStreamConstants.ENTITY_REFERENCE: // TODO: XMLEvent.ENTITY_REFERENCE? eventReader.nextEvent(); break; case XMLStreamConstants.START_DOCUMENT: // strange break; case XMLStreamConstants.START_ELEMENT: pmv = this.consumeNestedElement(eventReader, context); break; case XMLStreamConstants.END_ELEMENT: // TODO: in mixed content there will be more than one end element it this content model's level case XMLStreamConstants.END_DOCUMENT: end = true; break; } if (end) break; if (pmv != null) pmv.getMetadata().setValue(object, pmv.getValue()); } return (T) object; }
From source file:edu.harvard.iq.safe.lockss.impl.LOCKSSDaemonStatusTableXmlStreamParser.java
/** * * @param stream//from w ww . jav a 2 s .co m * @param encoding */ @Override public void read(InputStream stream, String encoding) { // logger.setLevel(Level.FINE); // 1. create Input factory XMLInputFactory xmlif = XMLInputFactory.newInstance(); xmlif.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE); xmlif.setProperty("javax.xml.stream.isNamespaceAware", java.lang.Boolean.TRUE); long startTime = System.currentTimeMillis(); int noAUs = 0; String aus = null; String currentTableId = null; String currentTableTitle = null; String currentTableKey = null; boolean hasErrorsColumn = false; String siAuId = null; XMLStreamReader xmlr = null; try { // create reader xmlr = xmlif.createXMLStreamReader(new BufferedInputStream(stream), encoding); String curElement = ""; boolean isLastTagnameTable = false; String targetTagName = "row"; String cellTagName = "columnname"; boolean withinSummaryinfo = false; boolean withinColumndescriptor = false; boolean withinRow = false; boolean withinCell = false; boolean withinReference = false; boolean isCrawlStatusActive = false; boolean isCrawlStatusColumn = false; int valueTagCounter = 0; String currentColumnName = null; String currentCellValue = null; String currentCellKey = null; SummaryInfo si = null; List<String> rowData = null; Map<String, String> rowDataH = null; w1: while (xmlr.hasNext()) { int eventType = xmlr.next(); switch (eventType) { case XMLStreamConstants.START_ELEMENT: curElement = xmlr.getLocalName(); // note: getName() -> // QName logger.log(Level.FINE, "--------- start tag = <{0}> ---------", curElement); // check the table name first if (curElement.equals("table")) { isLastTagnameTable = true; } else if (curElement.equals("error")) { isTargetPageValid = false; break w1; } if (isLastTagnameTable) { if (curElement.equals("name")) { currentTableId = xmlr.getElementText(); logger.log(Level.FINE, "########### table Id = [{0}] ###########", currentTableId); tableId = currentTableId; if (belongsInclusionTableList.contains(currentTableId)) { logger.log(Level.FINE, "!!!!! Table ({0}) belongs to the target list !!!!!", currentTableId); } else { logger.log(Level.FINE, "XXXXXXXXXXX Table ({0}) does not belong to the target list XXXXXXXXXXX", currentTableId); break w1; } } else if (curElement.equals("key")) { currentTableKey = xmlr.getElementText(); logger.log(Level.FINE, "---------- table key = ({0}) ----------", currentTableKey); tableKey = currentTableKey; } else if (curElement.equals("title")) { currentTableTitle = xmlr.getElementText(); logger.log(Level.FINE, "+++++++++ table Title = ({0}) +++++++++", currentTableTitle); if (currentTableId.equals("PeerRepair")) { if (currentTableTitle.startsWith("Repair candidates for AU: ")) { currentTableTitle = currentTableTitle.replaceFirst("Repair candidates for AU: ", ""); logger.log(Level.FINE, "save this modified table-Title as auName={0}", currentTableTitle); this.tableTitle = currentTableTitle; } else { logger.log(Level.WARNING, "The table-Title does not start with the expected token={0}", currentTableTitle); } } isLastTagnameTable = false; } } if (curElement.equals("columndescriptor")) { withinColumndescriptor = true; } else if (curElement.equals("row")) { withinRow = true; rowCounter++; logger.log(Level.FINE, "================== {0}-th row starts here ==================", rowCounter); // set-up the table storage //if (rowCounter == 1) { // 1st row rowData = new ArrayList<String>(); rowDataH = new LinkedHashMap<String, String>(); //} } else if (curElement.equals("cell")) { logger.log(Level.FINE, "entering a cell"); withinCell = true; } else if (curElement.equals("reference")) { withinReference = true; logger.log(Level.FINE, "within reference on"); } else if (curElement.equals("summaryinfo")) { withinSummaryinfo = true; si = new SummaryInfo(); } else if (curElement.equals("value")) { logger.log(Level.FINE, "entering a value"); valueTagCounter++; } //---- columndescriptor tag --------------------------------------------------- if (withinColumndescriptor) { if (curElement.equals("name")) { String nameText = xmlr.getElementText(); logger.log(Level.FINE, "\tcolumndescriptor: name = {0}", nameText); columndescriptorList.add(nameText); } else if (curElement.equals("title")) { String titleText = xmlr.getElementText(); logger.log(Level.FINE, "\tcolumndescriptor: title = {0}", titleText); } else if (curElement.equals("type")) { String typeText = xmlr.getElementText(); logger.log(Level.FINE, "\tcolumndescriptor: type = {0}", typeText); getTypeList().add(typeText); } } //---- cell tag ---------------------------------------------------------------- if (withinCell) { logger.log(Level.FINE, "parsing withinCell"); if (curElement.equals("columnname")) { String columnname = xmlr.getElementText(); logger.log(Level.FINE, "\t\tcolumnname = {0}", columnname); currentColumnName = columnname; if (columnname.equals("crawl_status")) { isCrawlStatusColumn = true; } else { isCrawlStatusColumn = false; } if (columnname.equals("Errors")) { hasErrorsColumn = true; } } else { // value tag block: either value-tag WO a child element // or with a child element /* * <value><reference>...<value>xxxx</value> * <value>xxxx</value> */ if ((curElement.equals("value")) && (!withinReference)) { logger.log(Level.FINE, "entering el:value/WO-REF block"); if (!hasReferenceTag.contains(currentColumnName)) { logger.log(Level.FINE, "No child reference tag is expected for this value tag"); logger.log(Level.FINEST, "xmlr.getEventType():pre-parsing={0}", xmlr.getEventType()); String cellValue = xmlr.getElementText(); // note: the above parsing action moves the // cursor to the end-tag, i.e., </value> // therefore, the end-element-switch-block below // cannot catch this </value> tag logger.log(Level.FINE, "\t\t\t[No ref: value] {0} = {1}", new Object[] { currentColumnName, cellValue }); currentCellValue = cellValue; logger.log(Level.FINEST, "xmlr.getEventType():post-parsing={0}", xmlr.getEventType()); // store this value // rowData logger.log(Level.FINE, "current column name={0}", currentColumnName); logger.log(Level.FINE, "valueTagCounter={0}", valueTagCounter); if (currentColumnName.endsWith("Damaged")) { if (valueTagCounter <= 1) { // 2nd value tag is footnot for this column // ignore this value rowData.add(cellValue); rowDataH.put(currentColumnName, currentCellValue); } } else { rowData.add(cellValue); rowDataH.put(currentColumnName, currentCellValue); } } else { // previously this block was unthinkable, but // it was found that there are columns that // temporarily have a <reference> tag in // crawl_status_table; these columns are // included in hasReferenceTag by default; // thus, for such unstable columns, // when they hava a <reference tag, // data are caputred in another within- // reference block; however, when these // columns no longer have <reference> tag, // text data would be left uncaptured unless // some follow-up processing takes place here logger.log(Level.FINE, "May have to capture data: column={0}", currentColumnName); if (mayHaveReferenceTag.contains(currentColumnName) && !isCrawlStatusActive) { // because the crawling is not active, // it is safely assume that the maybe columns have no reference tag // 2011-10-24 the above assumption was found wrong // a crawling cell does not say active but // subsequent columns have a reference logger.log(Level.FINE, "a text or a reference tag : try to parse it as a text"); String cellValue = null; try { cellValue = xmlr.getElementText(); } catch (javax.xml.stream.XMLStreamException ex) { continue; } finally { } logger.log(Level.FINE, "\t\t\t[value WO-ref(crawling_NOT_active case)={0}]", currentColumnName + " = " + cellValue); currentCellValue = cellValue; // store this value // rowData logger.log(Level.FINE, "\t\t\tcurrent columnName={0}", currentColumnName); rowData.add(cellValue); rowDataH.put(currentColumnName, currentCellValue); } else { logger.log(Level.FINE, "WO-Ref: no processing items now:{0}", curElement); } } } else if (withinReference) { // reference tag exists logger.log(Level.FINE, "WR:curElement={0}", curElement); if (curElement.equals("key")) { String cellKey = xmlr.getElementText(); logger.log(Level.FINE, "\t\tcurrentCellKey is set to={0}", cellKey); currentCellKey = cellKey; } else if (curElement.equals("value")) { String cellValue = xmlr.getElementText(); logger.log(Level.FINE, "\t\twr: {0} = {1}", new Object[] { currentColumnName, cellValue }); // exception cases follow: if (currentColumnName.equals("AuName")) { logger.log(Level.FINE, "\t\tAuName is replaced with the key[=AuId]= {0}", currentCellKey); // rowData // This block is for ArchivalUnitStatusTable // add the key as a new datum (auId) // ahead of its value rowData.add(currentCellKey); rowDataH.put("AuId", currentCellKey); currentCellValue = cellValue; } else if (currentColumnName.equals("auId")) { // This block is for V3PollerTable logger.log(Level.FINE, "\t\tnew value for auId(V3PollerTable)={0}", currentCellKey); // deprecated after 2012-02-02: use key as data // currentCellValue = currentCellKey; // add auName as a new column ahead of auId rowData.add(cellValue); rowDataH.put("auName", cellValue); logger.log(Level.FINE, "\t\tauName(V3PollerTable)={0}", cellValue); currentCellValue = currentCellKey; } else if (currentColumnName.equals("pollId")) { // this block is for V3PollerTable logger.log(Level.FINE, "\t\tFull string (key) is used={0}", currentCellKey); // The key has the complete string whereas // the value is its truncated copy currentCellValue = currentCellKey; } else if (currentColumnName.equals("au")) { logger.log(Level.FINE, "\t\tauId is used instead for au(crawl_status_table)={0}", currentCellKey); // 2012-02-02: add auName ahead of au rowData.add(cellValue); rowDataH.put("auName", cellValue); logger.log(Level.FINE, "\t\tauName={0}", cellValue); // rowData // This block is for crawl_status_table // save the key(auId) instead of value currentCellValue = currentCellKey; } else if (currentColumnName.equals("Peers")) { logger.log(Level.FINE, "\t\tURL (key) is used={0}", currentCellKey); currentCellValue = DaemonStatusDataUtil.escapeHtml(currentCellKey); logger.log(Level.FINE, "\t\tAfter encoding ={0}", currentCellValue); } else { if (isCrawlStatusColumn) { // if the craw status column is // "active", some later columns // may have a reference tag // so turn on the switch if (cellValue.equals("Active") || (cellValue.equals("Pending"))) { isCrawlStatusActive = true; } else { isCrawlStatusActive = false; } } // the default processing currentCellValue = cellValue; } // store currentCellValue logger.log(Level.FINE, "currentCellValue={0}", currentCellValue); // rowData rowData.add(currentCellValue); rowDataH.put(currentColumnName, currentCellValue); } // Within ref tag: key and valu processing } // value with text or value with ref tag } // columnname or value } // within cell // ---- summaryinfo tag -------------------------------------------------------- if (withinSummaryinfo) { logger.log(Level.FINE, "============================ Within SummaryInfo ============================ "); if (curElement.equals("title")) { String text = xmlr.getElementText(); si.setTitle(text); logger.log(Level.FINE, "\tsi:titile={0}", si.getTitle()); } else if (curElement.equals("type")) { String text = xmlr.getElementText(); si.setType(Integer.parseInt(text)); logger.log(Level.FINE, "\tsi:type={0}", si.getType()); } else if (curElement.equals("key")) { if (withinReference && si.getTitle().equals("Volume")) { String text = xmlr.getElementText(); logger.log(Level.FINE, "\tsi:key contents(Volume case)={0}", text); siAuId = text; // si.setValue(text); logger.log(Level.FINE, "\tsi:value(Volume case)={0}", siAuId); } } else if (curElement.equals("value")) { if (withinReference) { if (hasRefTitileTagsSI.contains(si.getTitle())) { if (si.getTitle().equals("Volume")) { // 2012-02-02 use the au name String text = xmlr.getElementText(); si.setValue(text); logger.log(Level.FINE, "\tsi:value(Volume case)={0}", si.getValue()); } else { String text = xmlr.getElementText(); si.setValue(text); logger.log(Level.FINE, "\tsi:value={0}", si.getValue()); } } } else { // note: 2012-02-07 // daemon 1.59.2 uses the new layout for AU page // this layout includes a summaryinfo tag // that now contains a reference tag String text = null; try { text = xmlr.getElementText(); if (!hasRefTitileTagsSI.contains(si.getTitle())) { si.setValue(text); logger.log(Level.FINE, "\tsi:value={0}", si.getValue()); } } catch (javax.xml.stream.XMLStreamException ex) { logger.log(Level.WARNING, "encounter a reference tag rather than text"); continue; } finally { } } } /* * aus = xmlr.getElementText(); * out.println("found token=[" + aus + "]"); if * (currentTableId.equals("ArchivalUnitStatusTable")) { * m = pau.matcher(aus); if (m.find()) { * out.println("How many AUs=" + m.group(1)); noAUs = * Integer.parseInt(m.group(1)); } else { * out.println("not found within[" + aus + "]"); } } */ } break; case XMLStreamConstants.CHARACTERS: break; case XMLStreamConstants.ATTRIBUTE: break; case XMLStreamConstants.END_ELEMENT: if (xmlr.getLocalName().equals("columndescriptor")) { withinColumndescriptor = false; logger.log(Level.FINE, "leaving columndescriptor"); } else if (xmlr.getLocalName().equals("row")) { if (withinRow) { logger.log(Level.FINE, "========= end of the target row element"); withinRow = false; } if (!isCrawlStatusActive) { tabularData.add(rowData); tableData.add(rowDataH); } else { rowIgnored++; rowCounter--; } rowData = null; rowDataH = null; isCrawlStatusActive = false; } else if (xmlr.getLocalName().equals("cell")) { // rowDataH.add(cellDatum); cellCounter++; withinCell = false; currentColumnName = null; currentCellValue = null; currentCellKey = null; isCrawlStatusColumn = false; valueTagCounter = 0; logger.log(Level.FINE, "leaving cell"); } else if (xmlr.getLocalName().equals("columnname")) { logger.log(Level.FINE, "leaving columnname"); } else if (xmlr.getLocalName().equals("reference")) { withinReference = false; } else if (xmlr.getLocalName().equals("summaryinfo")) { logger.log(Level.FINE, "si={0}", si.toString()); summaryInfoList.add(si); si = null; withinSummaryinfo = false; } else if (xmlr.getLocalName().equals("value")) { logger.log(Level.FINE, "leaving value"); } else { logger.log(Level.FINE, "--------- end tag = <{0}> ---------", curElement); } break; case XMLStreamConstants.END_DOCUMENT: logger.log(Level.FINE, "Total of {0} row occurrences", rowCounter); } // end: switch } // end:while } catch (XMLStreamException ex) { logger.log(Level.WARNING, "XMLStreamException occurs", ex); this.isTargetPageValid = false; } catch (RuntimeException re) { logger.log(Level.WARNING, "some RuntimeException occurs", re); this.isTargetPageValid = false; } catch (Exception e) { logger.log(Level.WARNING, "some Exception occurs", e); this.isTargetPageValid = false; } finally { // 5. close reader/IO if (xmlr != null) { try { xmlr.close(); } catch (XMLStreamException ex) { logger.log(Level.WARNING, "XMLStreamException occurs during close()", ex); } } if (!this.isTargetPageValid) { logger.log(Level.WARNING, "This parsing session may not be complete due to some exception reported earlier"); } } // end of try if (currentTableId.equals("V3PollerDetailTable")) { summaryInfoList.add(new SummaryInfo("auId", 4, siAuId)); summaryInfoMap = new LinkedHashMap<String, String>(); for (SummaryInfo si : summaryInfoList) { summaryInfoMap.put(si.getTitle(), si.getValue()); } } // parsing summary logger.log(Level.FINE, "###################### parsing summary ######################"); logger.log(Level.FINE, "currentTableId={0}", currentTableId); logger.log(Level.FINE, "currentTableTitle={0}", currentTableTitle); logger.log(Level.FINE, "currentTableKey={0}", currentTableKey); logger.log(Level.FINE, "columndescriptorList={0}", columndescriptorList); logger.log(Level.FINE, "# of columndescriptors={0}", columndescriptorList.size()); logger.log(Level.FINE, "typeList={0}", typeList); logger.log(Level.FINE, "# of rows counted={0}", rowCounter); logger.log(Level.FINE, "# of rows excluded[active ones are excluded]={0}", rowIgnored); logger.log(Level.FINE, "summaryInfoList:size={0}", summaryInfoList.size()); logger.log(Level.FINE, "summaryInfoList={0}", summaryInfoList); logger.log(Level.FINE, "table: cell counts = {0}", cellCounter); logger.log(Level.FINE, "tableData[map]=\n{0}", tableData); logger.log(Level.FINE, "tabularData[list]=\n{0}", tabularData); /* * if (currentTableId.equals("ArchivalUnitStatusTable")) { if * (rowCounter == noAUs) { out.println("au counting is OK=" + * rowCounter); } else { err.println("au counting disagreement"); throw * new RuntimeException("parsing error is suspected"); } } */ logger.log(Level.FINE, " completed in {0} ms\n\n", (System.currentTimeMillis() - startTime)); if (!columndescriptorList.isEmpty()) { int noCols = columndescriptorList.size(); if (currentTableId.equals("V3PollerTable") && !hasErrorsColumn) { noCols--; } int noCellsExpd = rowCounter * noCols; if (noCols > 0) { // this table has a table logger.log(Level.FINE, "checking parsing results: table dimmensions"); if (noCellsExpd == cellCounter) { logger.log(Level.FINE, "table dimensions and cell-count are consistent"); } else { int diff = noCellsExpd - cellCounter; logger.log(Level.FINE, "The table has {0} incomplete cells", diff); hasIncompleteRows = true; setIncompleteRowList(); logger.log(Level.FINE, "incomplete rows: {0}", incompleteRows); } } } }
From source file:ca.uhn.fhir.parser.XmlParser.java
private void encodeXhtml(XhtmlDt theDt, XMLStreamWriter theEventWriter) throws XMLStreamException { if (theDt == null || theDt.getValue() == null) { return;/*from www . java2 s . c o m*/ } boolean firstElement = true; for (XMLEvent event : theDt.getValue()) { switch (event.getEventType()) { case XMLStreamConstants.ATTRIBUTE: Attribute attr = (Attribute) event; if (isBlank(attr.getName().getPrefix())) { if (isBlank(attr.getName().getNamespaceURI())) { theEventWriter.writeAttribute(attr.getName().getLocalPart(), attr.getValue()); } else { theEventWriter.writeAttribute(attr.getName().getNamespaceURI(), attr.getName().getLocalPart(), attr.getValue()); } } else { theEventWriter.writeAttribute(attr.getName().getPrefix(), attr.getName().getNamespaceURI(), attr.getName().getLocalPart(), attr.getValue()); } break; case XMLStreamConstants.CDATA: theEventWriter.writeCData(((Characters) event).getData()); break; case XMLStreamConstants.CHARACTERS: case XMLStreamConstants.SPACE: String data = ((Characters) event).getData(); theEventWriter.writeCharacters(data); break; case XMLStreamConstants.COMMENT: theEventWriter.writeComment(((Comment) event).getText()); break; case XMLStreamConstants.END_ELEMENT: theEventWriter.writeEndElement(); break; case XMLStreamConstants.ENTITY_REFERENCE: EntityReference er = (EntityReference) event; theEventWriter.writeEntityRef(er.getName()); break; case XMLStreamConstants.NAMESPACE: Namespace ns = (Namespace) event; theEventWriter.writeNamespace(ns.getPrefix(), ns.getNamespaceURI()); break; case XMLStreamConstants.START_ELEMENT: StartElement se = event.asStartElement(); if (firstElement) { if (StringUtils.isBlank(se.getName().getPrefix())) { String namespaceURI = se.getName().getNamespaceURI(); if (StringUtils.isBlank(namespaceURI)) { namespaceURI = "http://www.w3.org/1999/xhtml"; } theEventWriter.writeStartElement(se.getName().getLocalPart()); theEventWriter.writeDefaultNamespace(namespaceURI); } else { String prefix = se.getName().getPrefix(); String namespaceURI = se.getName().getNamespaceURI(); theEventWriter.writeStartElement(prefix, se.getName().getLocalPart(), namespaceURI); theEventWriter.writeNamespace(prefix, namespaceURI); } firstElement = false; } else { if (isBlank(se.getName().getPrefix())) { if (isBlank(se.getName().getNamespaceURI())) { theEventWriter.writeStartElement(se.getName().getLocalPart()); } else { if (StringUtils.isBlank(se.getName().getPrefix())) { theEventWriter.writeStartElement(se.getName().getLocalPart()); // theEventWriter.writeDefaultNamespace(se.getName().getNamespaceURI()); } else { theEventWriter.writeStartElement(se.getName().getNamespaceURI(), se.getName().getLocalPart()); } } } else { theEventWriter.writeStartElement(se.getName().getPrefix(), se.getName().getLocalPart(), se.getName().getNamespaceURI()); } for (Iterator<?> attrIter = se.getAttributes(); attrIter.hasNext();) { Attribute next = (Attribute) attrIter.next(); theEventWriter.writeAttribute(next.getName().getLocalPart(), next.getValue()); } } break; case XMLStreamConstants.DTD: case XMLStreamConstants.END_DOCUMENT: case XMLStreamConstants.ENTITY_DECLARATION: case XMLStreamConstants.NOTATION_DECLARATION: case XMLStreamConstants.PROCESSING_INSTRUCTION: case XMLStreamConstants.START_DOCUMENT: break; } } }
From source file:org.apache.ode.utils.DOMUtils.java
private static void parse(XMLStreamReader reader, Document doc, Node parent) throws XMLStreamException { int event = reader.getEventType(); while (reader.hasNext()) { switch (event) { case XMLStreamConstants.START_ELEMENT: // create element Element e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName()); if (reader.getPrefix() != null && reader.getPrefix() != "") { e.setPrefix(reader.getPrefix()); }//from w w w . j av a2s . c o m parent.appendChild(e); // copy namespaces for (int ns = 0; ns < reader.getNamespaceCount(); ns++) { String uri = reader.getNamespaceURI(ns); String prefix = reader.getNamespacePrefix(ns); declare(e, uri, prefix); } // copy attributes for (int att = 0; att < reader.getAttributeCount(); att++) { String name = reader.getAttributeLocalName(att); String prefix = reader.getAttributePrefix(att); if (prefix != null && prefix.length() > 0) { name = prefix + ":" + name; } Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name); attr.setValue(reader.getAttributeValue(att)); e.setAttributeNode(attr); } // sub-nodes if (reader.hasNext()) { reader.next(); parse(reader, doc, e); } if (parent instanceof Document) { while (reader.hasNext()) reader.next(); return; } break; case XMLStreamConstants.END_ELEMENT: return; case XMLStreamConstants.CHARACTERS: if (parent != null) { parent.appendChild(doc.createTextNode(reader.getText())); } break; case XMLStreamConstants.COMMENT: if (parent != null) { parent.appendChild(doc.createComment(reader.getText())); } break; case XMLStreamConstants.CDATA: parent.appendChild(doc.createCDATASection(reader.getText())); break; case XMLStreamConstants.PROCESSING_INSTRUCTION: parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData())); break; case XMLStreamConstants.ENTITY_REFERENCE: parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData())); break; case XMLStreamConstants.NAMESPACE: case XMLStreamConstants.ATTRIBUTE: break; default: break; } if (reader.hasNext()) { event = reader.next(); } } }
From source file:org.mcisb.subliminal.SubliminalUtils.java
/** * /*from w w w .j a va 2 s.c o m*/ * @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; }
From source file:org.mule.module.xml.util.XMLUtils.java
public static void copy(XMLStreamReader reader, XMLStreamWriter writer, boolean fragment) throws XMLStreamException { // number of elements read in int read = 0; int event = reader.getEventType(); while (reader.hasNext()) { switch (event) { case XMLStreamConstants.START_ELEMENT: read++;//w ww.j a v a2s . c o m writeStartElement(reader, writer); break; case XMLStreamConstants.END_ELEMENT: writer.writeEndElement(); read--; if (read <= 0 && !fragment) { return; } break; case XMLStreamConstants.CHARACTERS: writer.writeCharacters(reader.getText()); break; case XMLStreamConstants.START_DOCUMENT: case XMLStreamConstants.END_DOCUMENT: case XMLStreamConstants.ATTRIBUTE: case XMLStreamConstants.NAMESPACE: break; default: break; } event = reader.next(); } }