List of usage examples for javax.xml.stream.events Attribute getName
QName getName();
From source file:com.amalto.core.load.io.XMLStreamUnwrapper.java
/** * Moves to next record in stream and stores it in {@link #stringWriter}. *//*from w w w . j a v a2 s .c om*/ private void moveToNext() { try { XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(stringWriter); boolean hasMadeChanges; do { if (!reader.hasNext()) { break; } hasMadeChanges = false; // Keep a state to skip line feeds final XMLEvent event = reader.nextEvent(); if (event.isEndElement()) { level--; } else if (event.isStartElement()) { level++; } else if (event.isEndDocument()) { level--; } if (level >= RECORD_LEVEL) { if (event.isEndElement()) { writer.writeEndElement(); hasMadeChanges = true; } else if (event.isStartElement()) { final StartElement startElement = event.asStartElement(); final QName name = startElement.getName(); writer.writeStartElement(name.getNamespaceURI(), name.getLocalPart()); boolean isRecordRootElement = (RECORD_LEVEL == level - 1); if (isRecordRootElement) { for (int i = 0; i < rootNamespaceList.size(); i++) { Namespace namespace = rootNamespaceList.get(i); writer.writeNamespace(namespace.getPrefix(), namespace.getNamespaceURI()); } } // Declare namespaces (if any) final Iterator elementNamespaces = startElement.getNamespaces(); while (elementNamespaces.hasNext()) { Namespace elementNamespace = (Namespace) elementNamespaces.next(); if (isRecordRootElement) { if (rootNamespaceList.size() > 0) { for (int i = 0; i < rootNamespaceList.size(); i++) { Namespace namespace = rootNamespaceList.get(i); if (!namespace.getPrefix().equals(elementNamespace.getPrefix()) || !namespace.getNamespaceURI() .equals(elementNamespace.getNamespaceURI())) { writer.writeNamespace(elementNamespace.getPrefix(), elementNamespace.getNamespaceURI()); } } } else { writer.writeNamespace(elementNamespace.getPrefix(), elementNamespace.getNamespaceURI()); } } else { writer.writeNamespace(elementNamespace.getPrefix(), elementNamespace.getNamespaceURI()); } } // Write attributes final Iterator attributes = startElement.getAttributes(); while (attributes.hasNext()) { Attribute attribute = (Attribute) attributes.next(); QName attributeName = attribute.getName(); String value = attribute.getValue(); if (StringUtils.isEmpty(attributeName.getNamespaceURI())) { writer.writeAttribute(attributeName.getLocalPart(), value); } else { writer.writeAttribute(attributeName.getNamespaceURI(), attributeName.getLocalPart(), value); } } hasMadeChanges = true; } else if (event.isCharacters()) { final String text = event.asCharacters().getData().trim(); if (!text.isEmpty()) { writer.writeCharacters(text); hasMadeChanges = true; } } } } while (level > RECORD_LEVEL || !hasMadeChanges); writer.flush(); } catch (XMLStreamException e) { throw new RuntimeException("Unexpected parsing exception.", e); } }
From source file:org.javelin.sws.ext.bind.internal.model.ComplexTypePattern.java
/** * @param eventReader/*ww w. j a v a2s . c o m*/ * @param context * @return */ private PropertyMetadataValue<T, ?> consumeNestedAttribute(XMLEventReader eventReader, UnmarshallingContext context) throws XMLStreamException { Attribute attr = (Attribute) eventReader.peek(); QName qName = attr.getName(); return this.consumeNestedProperty(this.attributes.get(qName), eventReader, context); }
From source file:com.streamsets.pipeline.lib.xml.StreamingXmlParser.java
String getName(String namePrefix, Attribute element) { return getName(element.getName(), namePrefix); }
From source file:com.joliciel.frenchTreebank.upload.TreebankXmlReader.java
public void startElement(StartElement startElementEvent) { String qName = startElementEvent.getName().getLocalPart(); @SuppressWarnings("rawtypes") Iterator iAttributes = startElementEvent.getAttributes(); Map<String, String> attributes = new HashMap<String, String>(); while (iAttributes.hasNext()) { Attribute attribute = (Attribute) iAttributes.next(); String name = attribute.getName().getLocalPart(); String value = attribute.getValue(); attributes.put(name, value);//from w ww . j av a2 s . co m } // clear out tempVal whenever a new element is started tempVal = ""; if (qName.equalsIgnoreCase("SENT")) { // a new sentence sentence = treebankService.newSentence(); String sentenceNumber = attributes.get("nb"); if (LOG.isDebugEnabled()) LOG.debug("Sentence number " + sentenceNumber); sentence.setSentenceNumber(sentenceNumber); sentence.setFile(treebankFile); } else if (qName.equalsIgnoreCase("w")) { // a new word or compound word if (phraseUnit == null) { String categoryCode = attributes.get("cat"); String subCategoryCode = attributes.get("subcat"); String morphologyCode = attributes.get("mph"); String lemma = attributes.get("lemma"); boolean isCompound = false; String isCompoundStr = attributes.get("compound"); if (isCompoundStr != null && isCompoundStr.equalsIgnoreCase("yes")) isCompound = true; String compoundId = attributes.get("id"); String compoundNextId = attributes.get("next"); String compoundPrevId = attributes.get("prev"); //String isCompound = attributes.getValue("compound"); // ignoring compound attribute as not reliable - instead relying on embedded words to indicate a compound phrase unit if (LOG.isTraceEnabled()) LOG.trace("Opening w " + lemma); phraseUnit = sentence.newPhraseUnit(categoryCode, subCategoryCode, morphologyCode, lemma, isCompound, compoundId, compoundNextId, compoundPrevId); String word = attributes.get("word"); if (word != null) { phraseUnit.setText(word); } } else { isPhraseUnitCompound = true; String categoryCode = attributes.get("catint"); String subCategoryCode = attributes.get("subcat"); String morphologyCode = attributes.get("mph"); if (LOG.isTraceEnabled()) LOG.trace("Opening subunit " + categoryCode); phraseSubunit = phraseUnit.newSubunit(categoryCode, subCategoryCode, morphologyCode); } } else if (qName.equalsIgnoreCase("sentence")) { // ignore for now, will only be treated in end element } else if (qName.equalsIgnoreCase("text")) { // top level text tag, we don't need to do nothing } else { // must be a phrase if (sentence != null) { String functionCode = attributes.get("fct"); if (LOG.isTraceEnabled()) LOG.trace("Opening phrase " + qName + ", " + functionCode); sentence.openPhrase(qName, functionCode); } } }
From source file:eu.delving.sip.xml.SourceConverter.java
private void handleAttribute(Path path, Attribute attr) { Path extended = path.child(Tag.attribute(attr.getName())); if (extended.equals(uniqueElementPath)) { unique = attr.getValue();/*from w w w . j a v a2s .co m*/ } else if (path.equals(recordRootPath)) { QName a = attr.getName(); QName attrName = new QName(a.getNamespaceURI(), "_" + a.getLocalPart(), a.getPrefix()); eventBuffer.add(eventFactory.createStartElement(attrName, null, null)); eventBuffer.add(eventFactory.createCharacters(attr.getValue())); eventBuffer.add(eventFactory.createEndElement(attrName, null)); eventBuffer.add(eventFactory.createCharacters("\n")); } }
From source file:eu.delving.sip.xml.SourceConverter.java
private Iterator<Attribute> filteredAttributes() { Iterator aw = start.getAttributes(); List<Attribute> attributes = new ArrayList<Attribute>(); while (aw.hasNext()) { Attribute attribute = (Attribute) aw.next(); if (XSI_SCHEMA.equals(attribute.getName().getNamespaceURI())) continue; attributes.add(attribute);/*from ww w.j av a 2s . co m*/ } return attributes.iterator(); }
From source file:com.prowidesoftware.swift.model.mx.XmlEventWriter.java
public void add(final XMLEvent event) throws XMLStreamException { if (event != null) { log.finest("XmlEventType: " + event.getEventType()); try {/* w w w . j ava 2 s.c o m*/ final int type = event.getEventType(); switch (type) { case XMLEvent.START_DOCUMENT: if (this.includeXMLDeclaration) { log.finer(">> START_DOCUMENT"); log.finer("START_DOCUMENT XMLEvent " + ToStringBuilder.reflectionToString(event)); final String str = "<?xml version=\"1.0\" encoding=\"" + ((StartDocument) event).getCharacterEncodingScheme() + "\"?>"; out.write(str); logStep(str); } else { log.finer("skipping xml declaration"); } break; case XMLEvent.START_ELEMENT: this.startElementCount++; closeStartTagIfNeeded(); log.finer(">> START_ELEMENT"); indent.append(' '); final StartElement se = event.asStartElement(); @SuppressWarnings("rawtypes") final Iterator it = se.getNamespaces(); while (it.hasNext()) { log.fine("ns: " + it.next()); } /*--------------------------------------------------------------------------------------- * 2015.03 miguel * Cuidado con esta condicion! esto generaba el bug de que no abria el Document anidado dentro del xs:any * Esto es porque este document delayed solo se completa cuando recibe un namespace, pensado como elemento inicial * esto DEEEEBEEEEEEEEEEe corregirse cuando se cambie la serializacion, si se cambia * porque si el document queda dentro de un elemento payload, entonces en count es != 1 y debe revisarse como se identifica el primer * document y un document anidado. * */ if (StringUtils.equals(se.getName().getLocalPart(), this.rootElement) && this.startElementCount == 1) { // 2015.03 miguel: ESTE era el bug de esprow, que aparecian tags anidados de document cerrando que no abria, era porque entraban por aca sin esta condicion de depth count delayedStart = se; log.finer("local part is Document, initializing delayed start, startElementCount=" + this.startElementCount); } else { final String s = "\n" + indent + "<" + prefix() + se.getName().getLocalPart() /* + ">" */; out.write(s); logStep(s); /* 2014.11 miguel * para soportar atributos en lugar de cerrar aca seteamos un flag para indicar * que hace falta cerrar el startTag */ startTagIncomplete = true; if (se.isNamespace()) { log.fine("is ns in start XMLEvent " + ToStringBuilder.reflectionToString(event)); } } break; case XMLEvent.NAMESPACE: log.finer(">> NAMESPACE"); final Namespace ne = (Namespace) event; if (delayedStart != null) { final String s = "\n" + indent + "<" + prefix() + delayedStart.getName().getLocalPart() + " " + "xmlns" + (this.prefix != null ? ":" + this.prefix : "") + "=\"" + ne.getValue() + "\" xmlns:xsi=\"" + ne.getName() + "\"" + ">"; out.write(s); logStep(s); delayedStart = null; } else { log.fine("NAMESPACE XMLEvent " + ToStringBuilder.reflectionToString(event)); } break; case XMLEvent.CHARACTERS: log.finer(">> CHARACTERS"); closeStartTagIfNeeded(); final Characters ce = event.asCharacters(); final char[] arr = ce.getData().toCharArray(); out.write(escape(arr)); logStep(ce.getData()); break; case XMLEvent.END_ELEMENT: log.finer(">> END_ELEMENT"); closeStartTagIfNeeded(); indent.deleteCharAt(0); final EndElement ee = event.asEndElement(); final String str2 = "</" + prefix() + ee.getName().getLocalPart() + ">\n" + indent; out.write(str2); logStep(str2); break; case XMLEvent.END_DOCUMENT: log.finer(">> END_DOCUMENT"); closeStartTagIfNeeded(); /* 2014.10 miguel * No need to do anything while writing to a string */ log.finer("END_DOCUMENT XMLEvent " + ToStringBuilder.reflectionToString(event)); break; case XMLEvent.ATTRIBUTE: log.finer(">> ATTRIBUTE"); final Attribute a = (Attribute) event; final String str3 = " " + a.getName() + "=\"" + a.getValue() + "\" "; out.write(str3); log.fine(ToStringBuilder.reflectionToString(a)); logStep(str3); break; default: log.info("getEventType " + event.getEventType()); log.info("PW Unhandled XMLEvent " + ToStringBuilder.reflectionToString(event)); break; } } catch (IOException e) { log.log(Level.SEVERE, "PW I/O error: " + e); log.log(Level.FINER, "PW I/O error: ", e); throw new XMLStreamException(e); } } }
From source file:com.google.code.activetemplates.impl.TemplateCompilerImpl.java
private void doCompile(String name, CompileContext cc) throws XMLStreamException { while (cc.hasNextEvent()) { XMLEvent e = cc.nextEvent(); //Location loc = e.getLocation(); if (e.isAttribute()) { //System.out.println("Adding " + e); // attributes added during tag processing and under the same tag // get handled here, outcome is always PROCESS_ALL Attribute a = (Attribute) e; if (h.isAttributeHandled(a.getName())) { h.processAttribute(cc, a); } else { String value = a.getValue(); String nvalue = processText(cc, value); if (nvalue != null) { a = cc.getElementFactory().createAttribute(a.getName(), nvalue); }//from w w w . j a v a 2s. c o m //System.out.println("Adding " + e); cc.getWriter().add(a); } } else if (e.isStartElement()) { StartElement se = e.asStartElement(); Processing processing = Processing.DEFAULT; // collect namespaces @SuppressWarnings("unchecked") Iterator<Namespace> nsit = se.getNamespaces(); List<Namespace> namespaces = new ArrayList<Namespace>(); while (nsit.hasNext()) { Namespace ns = nsit.next(); if (excludedNamespaces.contains(ns.getNamespaceURI())) { processing = Processing.REPLACE; } else { namespaces.add(ns); } } // collect attributes @SuppressWarnings("unchecked") Iterator<Attribute> it = se.getAttributes(); List<Attribute> attributes = new LinkedList<Attribute>(); while (it.hasNext()) { attributes.add(it.next()); } // collect any separate attribute and namespace xml events while (cc.hasNextEvent()) { if (cc.peekEvent().isNamespace()) { namespaces.add((Namespace) cc.nextEvent()); processing = Processing.REPLACE; } else if (cc.peekEvent().isAttribute()) { attributes.add((Attribute) cc.nextEvent()); processing = Processing.REPLACE; } else { break; } } // preprocess attributes it = attributes.iterator(); attributes = new ArrayList<Attribute>(); while (it.hasNext() && processing != Processing.SKIP) { Attribute a = it.next(); if (h.isAttributeHandled(a.getName())) { processing = Processing.REPLACE; AttributeHandler.Outcome o = h.processAttribute(cc, a); if (o == Outcome.PROCESS_NONE) { processing = Processing.SKIP; } } else { String value = a.getValue(); String nvalue = processText(cc, value); if (nvalue != null) { a = cc.getElementFactory().createAttribute(a.getName(), nvalue); processing = Processing.REPLACE; } attributes.add(a); } } if (processing == Processing.SKIP) { skipChildren(cc, false); } else { if (processing == Processing.REPLACE) { // replace element with new one se = cc.getElementFactory().createStartElement(se.getName(), attributes.iterator(), namespaces.iterator()); } // handle start element if (h.isElementHandled(se.getName())) { ElementHandler.Outcome o = h.processStartElement(cc, se); cc.flushEventQueue(); switch (o) { case PROCESS_SIBLINGS: skipChildren(cc, true); break; } } else { //System.out.println("Adding " + se); cc.getWriter().add(se); cc.flushEventQueue(); // flush events added by any attribute handlers } } } else if (e.isEndElement()) { // handle end element if (h.isElementHandled(e.asEndElement().getName())) { h.processEndElement(cc, e.asEndElement()); cc.flushEventQueue(); } else { //System.out.println("Adding " + e); cc.getWriter().add(e); } } else if (e.isCharacters()) { // process text Characters ce = e.asCharacters(); String s = ce.getData(); String ns = processText(cc, s); if (ns != null) { ce = cc.getElementFactory().createCharacters(ns); } //System.out.println("Adding " + e); cc.getWriter().add(ce); } } }
From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java
/** * If the reference is a attribute (e.g. sawsdl:modelreference), we add it here (by creating * the according XMLEvent). The ref// w w w . j a v a 2 s . c om * @param w * @param ref * @param se * @throws XMLStreamException */ private StartElement handleAttribute(XMLEventWriter w, Reference ref, StartElement se) throws XMLStreamException { /* we are having attributes which are in both, the reference and the current element. We only add * a new Attribute event, if it is not already contained in the Start Element * * Example: * reference <element ns:attr1="value" reference="http://example.com"> * element <element ns:attr1="value"> */ StringBuilder referenceString = new StringBuilder(ref.getTarget().toString()); Matcher matcher = findAttributeInReference.matcher(referenceString); List<Attribute> attributeList = new ArrayList<Attribute>(); // copy namespaces LocalNamespaceContext lnc = new LocalNamespaceContext((BaseNsContext) se.getNamespaceContext()); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String key = null; String prefix = null; String value = null; // [ns:attr1, "value"] String[] l = referenceString.substring(start, end).split("="); if (l.length > 0) { // [ns, attr1] String[] n = l[0].split(":"); if (n.length == 2) { key = n[1]; prefix = n[0]; } else { key = n[0]; } if (l.length == 2) { value = l[1].substring(1, l[1].length() - 1); // remove "" } } // check if this is a namespace definition if ((prefix != null) && ("xmlns".contentEquals(prefix))) { lnc.put(key, value); } else { QName name = null; // create QName if (prefix != null) { name = new QName(null, key, prefix); } else { String namespaceURI = se.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX); name = new QName(namespaceURI, key); } if (name != null) { Attribute created = getXMLEventFactory().createAttribute(name, value); attributeList.add(created); } } } // remove redundant attribute from reference list Iterator<?> it = se.getAttributes(); while (it.hasNext()) { Attribute ae = (Attribute) it.next(); for (Attribute ar : attributeList) { if ((ar.getName().getLocalPart().contentEquals(ae.getName().getLocalPart())) && (ar.getValue().contentEquals(ae.getValue()))) { //System.out.println("Attribute removed! -> " + ar.getName() + "= " + ar.getValue()); attributeList.remove(ar); break; } } } // merge everything again Iterator<? extends Attribute> it2 = se.getAttributes(); while (it2.hasNext()) { attributeList.add(it2.next()); } // create a new element with the attribute set and return it return StartElementEventImpl.construct(se.getLocation(), se.getName(), attributeList.iterator(), lnc.getNamespaces().iterator(), lnc); }
From source file:com.logiware.accounting.domain.EdiInvoice.java
private void setElementType(StartElement startElement) { if (isHeader) { if ("Applicationreference".equalsIgnoreCase(startElement.getName().toString())) { elementType = "Applicationreference"; elements.add("Applicationreference"); } else if ("Reference".equalsIgnoreCase(startElement.getName().toString())) { elementType = "Reference"; elements.add("Reference"); } else if ("Sender".equalsIgnoreCase(startElement.getName().toString())) { elementType = "Sender"; elements.add("Sender"); }//w w w.j a v a2 s. c o m } else if (isBody) { if (isInformation) { if ("Invoice".equalsIgnoreCase(startElement.getName().toString())) { elementType = "Invoice"; elements.add("Invoice"); } else if ("RelatedReferences".equalsIgnoreCase(startElement.getName().toString())) { elementType = "RelatedReferences"; elements.add("RelatedReferences"); } else if ("Parties".equalsIgnoreCase(startElement.getName().toString())) { Iterator attributes = startElement.getAttributes(); if (attributes.hasNext()) { Attribute attribute = (Attribute) (attributes.next()); if ("Qualifier".equals(attribute.getName().toString())) { if ("BY".equals(attribute.getValue())) { elementType = "Company"; elements.add("BY"); } else if ("SU".equals(attribute.getValue())) { elementType = "Vendor"; elements.add("SU"); } } } } else if ("PaymentTerms".equalsIgnoreCase(startElement.getName().toString())) { elementType = "PaymentTerms"; elements.add("PaymentTerms"); } else if ("ShipmentInformation".equalsIgnoreCase(startElement.getName().toString())) { elementType = "ShipmentInformation"; elements.add("ShipmentInformation"); } } else if (isDetails) { if ("Detail".equalsIgnoreCase(startElement.getName().toString())) { elementType = "Detail"; elements.add("Detail"); } } else if (isSummary) { if ("TotalMonetaryAmount".equalsIgnoreCase(startElement.getName().toString())) { elementType = "TotalMonetaryAmount"; elements.add("TotalMonetaryAmount"); } else if ("TotalMonetaryAmountGroupByVAT".equalsIgnoreCase(startElement.getName().toString())) { elementType = "TotalMonetaryAmountGroupByVAT"; elements.add("TotalMonetaryAmountGroupByVAT"); } } } }