List of usage examples for javax.xml.stream.events StartElement getNamespaces
public Iterator<Namespace> getNamespaces();
From source file:Main.java
private static void writeAsEncodedUnicode(StartElement element, Writer writer, boolean isEmpty) throws XMLStreamException { try {//from w w w . j a v a2s. c o m // Write start tag. writer.write('<'); QName name = element.getName(); String prefix = name.getPrefix(); if (prefix != null && prefix.length() > 0) { writer.write(prefix); writer.write(':'); } writer.write(name.getLocalPart()); // Write namespace declarations. Iterator nsIter = element.getNamespaces(); while (nsIter.hasNext()) { Namespace ns = (Namespace) nsIter.next(); writer.write(' '); ns.writeAsEncodedUnicode(writer); } // Write attributes Iterator attrIter = element.getAttributes(); while (attrIter.hasNext()) { Attribute attr = (Attribute) attrIter.next(); writer.write(' '); attr.writeAsEncodedUnicode(writer); } if (isEmpty) writer.write('/'); writer.write('>'); } catch (IOException ioe) { throw new XMLStreamException(ioe); } }
From source file:Main.java
/** * Constructs a new StartElement that merges the attributes and namespaces * found in the specified StartElement, with the provided attributes. The * returned StartElement will contain all the attributes and namespaces of * the original, plus those defined in the map. * /*from www .jav a2 s .co m*/ * @param tag The original StartElement * @param attrs An iterator of Atributes to add to the element. * @return A new StartElement that contains all the original attributes and * namespaces, plus the provided attributes. */ public static StartElement mergeAttributes(StartElement tag, Iterator attrs, XMLEventFactory factory) { // create Attribute map Map attributes = new HashMap(); // iterate through start tag's attributes for (Iterator i = tag.getAttributes(); i.hasNext();) { Attribute attr = (Attribute) i.next(); attributes.put(attr.getName(), attr); } // iterate through new attributes while (attrs.hasNext()) { Attribute attr = (Attribute) attrs.next(); attributes.put(attr.getName(), attr); } factory.setLocation(tag.getLocation()); QName tagName = tag.getName(); return factory.createStartElement(tagName.getPrefix(), tagName.getNamespaceURI(), tagName.getLocalPart(), attributes.values().iterator(), tag.getNamespaces(), tag.getNamespaceContext()); }
From source file:Main.java
/** * Like {@link javanet.staxutils.XMLStreamUtils#mergeAttributes} but it can * also merge namespaces/*from w w w . ja v a2 s. c o m*/ * * @param tag * @param attrs * @param nsps */ public static StartElement mergeAttributes(StartElement tag, Iterator<? extends Attribute> attrs, Iterator<? extends Namespace> nsps, XMLEventFactory factory) { // create Attribute map Map<QName, Attribute> attributes = new HashMap<QName, Attribute>(); // iterate through start tag's attributes for (Iterator i = tag.getAttributes(); i.hasNext();) { Attribute attr = (Attribute) i.next(); attributes.put(attr.getName(), attr); } if (attrs != null) { // iterate through new attributes while (attrs.hasNext()) { Attribute attr = attrs.next(); attributes.put(attr.getName(), attr); } } Map<QName, Namespace> namespaces = new HashMap<QName, Namespace>(); for (Iterator i = tag.getNamespaces(); i.hasNext();) { Namespace ns = (Namespace) i.next(); namespaces.put(ns.getName(), ns); } if (nsps != null) { while (nsps.hasNext()) { Namespace ns = nsps.next(); namespaces.put(ns.getName(), ns); } } factory.setLocation(tag.getLocation()); QName tagName = tag.getName(); return factory.createStartElement(tagName.getPrefix(), tagName.getNamespaceURI(), tagName.getLocalPart(), attributes.values().iterator(), namespaces.values().iterator(), tag.getNamespaceContext()); }
From source file:com.amalto.core.load.io.XMLStreamUnwrapper.java
public XMLStreamUnwrapper(InputStream stream) { try {//w w w .j a va 2s. c o m reader = XMLInputFactory.newFactory().createXMLEventReader(stream); // Skip to first record while (reader.hasNext() && level < RECORD_LEVEL) { final XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { // Declare root element namespaces (if any) final StartElement startElement = event.asStartElement(); Iterator namespaces = startElement.getNamespaces(); while (namespaces.hasNext()) { rootNamespaceList.add((Namespace) namespaces.next()); } level++; } } xmlOutputFactory = XMLOutputFactory.newFactory(); } catch (XMLStreamException e) { throw new RuntimeException("Unexpected parsing configuration error.", e); } }
From source file:com.predic8.membrane.core.ws.relocator.Relocator.java
@SuppressWarnings("unchecked") private XMLEvent replace(XMLEvent event, String attribute) { StartElement startElement = event.asStartElement(); return fac.createStartElement(startElement.getName(), new ReplaceIterator(fac, attribute, startElement.getAttributes()), startElement.getNamespaces()); }
From source file:com.xiongyingqi.util.xml.XMLEventStreamWriter.java
private void writeStartElement(StartElement startElement) throws XMLStreamException { eventWriter.add(startElement);//w ww . j a v a 2s . co m endElements.add(eventFactory.createEndElement(startElement.getName(), startElement.getNamespaces())); }
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 {//from w w w.j a v a 2 s. c om 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.streamsets.pipeline.lib.xml.StreamingXmlParser.java
Map<String, Field> toField(StartElement startE) { Map<String, Field> map = new LinkedHashMap<>(); Iterator attrs = startE.getAttributes(); while (attrs.hasNext()) { Attribute attr = (Attribute) attrs.next(); map.put(getName(ATTR_PREFIX_KEY, attr), Field.create(attr.getValue())); }/* w ww .ja va 2 s .com*/ Iterator nss = startE.getNamespaces(); while (nss.hasNext()) { Namespace ns = (Namespace) nss.next(); map.put(getName(NS_PREFIX_KEY, ns), Field.create(ns.getNamespaceURI())); } return map; }
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); }/* w ww. j a v a 2s.co 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:com.amalto.core.load.io.XMLStreamUnwrapper.java
/** * Moves to next record in stream and stores it in {@link #stringWriter}. *///from www. ja va 2s . com 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); } }