Example usage for javax.xml.stream XMLStreamWriter writeNamespace

List of usage examples for javax.xml.stream XMLStreamWriter writeNamespace

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter writeNamespace.

Prototype

public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException;

Source Link

Document

Writes a namespace to the output stream If the prefix argument to this method is the empty string, "xmlns", or null this method will delegate to writeDefaultNamespace

Usage

From source file:com.amalto.core.load.io.XMLStreamUnwrapper.java

/**
 * Moves to next record in stream and stores it in {@link #stringWriter}.
 *//*from  w ww.  j  a v  a2s . 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:ca.uhn.fhir.parser.XmlParser.java

private void encodeBundleToWriterDstu1(Bundle theBundle, XMLStreamWriter eventWriter)
        throws XMLStreamException {
    eventWriter.writeStartElement("feed");
    eventWriter.writeDefaultNamespace(ATOM_NS);

    writeTagWithTextNode(eventWriter, "title", theBundle.getTitle());
    writeTagWithTextNode(eventWriter, "id", theBundle.getBundleId());

    writeAtomLink(eventWriter, Constants.LINK_SELF, theBundle.getLinkSelf());
    writeAtomLink(eventWriter, Constants.LINK_FIRST, theBundle.getLinkFirst());
    writeAtomLink(eventWriter, Constants.LINK_PREVIOUS, theBundle.getLinkPrevious());
    writeAtomLink(eventWriter, Constants.LINK_NEXT, theBundle.getLinkNext());
    writeAtomLink(eventWriter, Constants.LINK_LAST, theBundle.getLinkLast());
    writeAtomLink(eventWriter, Constants.LINK_FHIR_BASE, theBundle.getLinkBase());

    if (theBundle.getTotalResults().getValue() != null) {
        eventWriter.writeStartElement("os", "totalResults", OPENSEARCH_NS);
        eventWriter.writeNamespace("os", OPENSEARCH_NS);
        eventWriter.writeCharacters(theBundle.getTotalResults().getValue().toString());
        eventWriter.writeEndElement();/* w  ww  . j  av a  2s .  co m*/
    }

    writeOptionalTagWithTextNode(eventWriter, "updated", theBundle.getUpdated());

    writeAuthor(eventWriter, theBundle);

    writeCategories(eventWriter, theBundle.getCategories());

    for (BundleEntry nextEntry : theBundle.getEntries()) {
        boolean deleted = false;
        if (nextEntry.getDeletedAt() != null && nextEntry.getDeletedAt().isEmpty() == false) {
            deleted = true;
            eventWriter.writeStartElement("at", "deleted-entry", TOMBSTONES_NS);
            eventWriter.writeNamespace("at", TOMBSTONES_NS);

            if (nextEntry.getDeletedResourceId().isEmpty()) {
                writeOptionalAttribute(eventWriter, "ref", nextEntry.getId().getValueAsString());
            } else {
                writeOptionalAttribute(eventWriter, "ref", nextEntry.getDeletedResourceId().getValueAsString());
            }

            writeOptionalAttribute(eventWriter, "when", nextEntry.getDeletedAt().getValueAsString());
            if (nextEntry.getDeletedByEmail().isEmpty() == false
                    || nextEntry.getDeletedByName().isEmpty() == false) {
                eventWriter.writeStartElement(TOMBSTONES_NS, "by");
                if (nextEntry.getDeletedByName().isEmpty() == false) {
                    eventWriter.writeStartElement(TOMBSTONES_NS, "name");
                    eventWriter.writeCharacters(nextEntry.getDeletedByName().getValue());
                    eventWriter.writeEndElement();
                }
                if (nextEntry.getDeletedByEmail().isEmpty() == false) {
                    eventWriter.writeStartElement(TOMBSTONES_NS, "email");
                    eventWriter.writeCharacters(nextEntry.getDeletedByEmail().getValue());
                    eventWriter.writeEndElement();
                }
                eventWriter.writeEndElement();
            }
            if (nextEntry.getDeletedComment().isEmpty() == false) {
                eventWriter.writeStartElement(TOMBSTONES_NS, "comment");
                eventWriter.writeCharacters(nextEntry.getDeletedComment().getValue());
                eventWriter.writeEndElement();
            }
        } else {
            eventWriter.writeStartElement("entry");
        }

        writeOptionalTagWithTextNode(eventWriter, "title", nextEntry.getTitle());
        if (!deleted) {
            if (nextEntry.getId().isEmpty() == false) {
                writeTagWithTextNode(eventWriter, "id", nextEntry.getId());
            } else {
                writeTagWithTextNode(eventWriter, "id", nextEntry.getResource().getId());
            }
        }
        writeOptionalTagWithTextNode(eventWriter, "updated", nextEntry.getUpdated());
        writeOptionalTagWithTextNode(eventWriter, "published", nextEntry.getPublished());

        writeAuthor(eventWriter, nextEntry);

        writeCategories(eventWriter, nextEntry.getCategories());

        if (!nextEntry.getLinkSelf().isEmpty()) {
            writeAtomLink(eventWriter, "self", nextEntry.getLinkSelf());
        }

        if (!nextEntry.getLinkAlternate().isEmpty()) {
            writeAtomLink(eventWriter, "alternate", nextEntry.getLinkAlternate());
        }

        if (!nextEntry.getLinkSearch().isEmpty()) {
            writeAtomLink(eventWriter, "search", nextEntry.getLinkSearch());
        }

        IResource resource = nextEntry.getResource();
        if (resource != null && !resource.isEmpty() && !deleted) {
            eventWriter.writeStartElement("content");
            eventWriter.writeAttribute("type", "text/xml");
            encodeResourceToXmlStreamWriter(resource, eventWriter, false, true);
            eventWriter.writeEndElement(); // content
        } else {
            ourLog.debug("Bundle entry contains null resource");
        }

        if (!nextEntry.getSummary().isEmpty()) {
            eventWriter.writeStartElement("summary");
            eventWriter.writeAttribute("type", "xhtml");
            encodeXhtml(nextEntry.getSummary(), eventWriter);
            eventWriter.writeEndElement();
        }

        eventWriter.writeEndElement(); // entry
    }

    eventWriter.writeEndElement();
    eventWriter.close();
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleGetContainerAcl(HttpServletResponse response, BlobStore blobStore, String containerName)
        throws IOException {
    ContainerAccess access = blobStore.getContainerAccess(containerName);

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();/*from w w w.  j a  v  a  2s. c  o m*/
        xml.writeStartElement("AccessControlPolicy");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeOwnerStanza(xml);

        xml.writeStartElement("AccessControlList");

        xml.writeStartElement("Grant");

        xml.writeStartElement("Grantee");
        xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xml.writeAttribute("xsi:type", "CanonicalUser");

        writeSimpleElement(xml, "ID", FAKE_OWNER_ID);
        writeSimpleElement(xml, "DisplayName", FAKE_OWNER_DISPLAY_NAME);

        xml.writeEndElement();

        writeSimpleElement(xml, "Permission", "FULL_CONTROL");

        xml.writeEndElement();

        if (access == ContainerAccess.PUBLIC_READ) {
            xml.writeStartElement("Grant");

            xml.writeStartElement("Grantee");
            xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xml.writeAttribute("xsi:type", "Group");

            writeSimpleElement(xml, "URI", "http://acs.amazonaws.com/groups/global/AllUsers");

            xml.writeEndElement();

            writeSimpleElement(xml, "Permission", "READ");

            xml.writeEndElement();
        }

        xml.writeEndElement();

        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleGetBlobAcl(HttpServletResponse response, BlobStore blobStore, String containerName,
        String blobName) throws IOException {
    BlobAccess access = blobStore.getBlobAccess(containerName, blobName);

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();/*from  ww  w .  j  a  va  2  s  .  com*/
        xml.writeStartElement("AccessControlPolicy");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeOwnerStanza(xml);

        xml.writeStartElement("AccessControlList");

        xml.writeStartElement("Grant");

        xml.writeStartElement("Grantee");
        xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xml.writeAttribute("xsi:type", "CanonicalUser");

        writeSimpleElement(xml, "ID", FAKE_OWNER_ID);
        writeSimpleElement(xml, "DisplayName", FAKE_OWNER_DISPLAY_NAME);

        xml.writeEndElement();

        writeSimpleElement(xml, "Permission", "FULL_CONTROL");

        xml.writeEndElement();

        if (access == BlobAccess.PUBLIC_READ) {
            xml.writeStartElement("Grant");

            xml.writeStartElement("Grantee");
            xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xml.writeAttribute("xsi:type", "Group");

            writeSimpleElement(xml, "URI", "http://acs.amazonaws.com/groups/global/AllUsers");

            xml.writeEndElement();

            writeSimpleElement(xml, "Permission", "READ");

            xml.writeEndElement();
        }

        xml.writeEndElement();

        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

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;//  www. jav a 2  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:nl.nn.adapterframework.soap.Wsdl.java

/**
 * Writes the WSDL to an output stream/*from  w  w w . j a  v a2  s.  c o  m*/
 * @param out
 * @param servlet  The servlet what is used as the web service (because this needs to be present in the WSDL)
 * @throws XMLStreamException
 * @throws IOException
 */
public void wsdl(OutputStream out, String servlet)
        throws XMLStreamException, IOException, ConfigurationException, NamingException {
    XMLStreamWriter w = WsdlUtils.getWriter(out, isIndent());

    w.writeStartDocument(XmlUtils.STREAM_FACTORY_ENCODING, "1.0");
    w.setPrefix(WSDL_NAMESPACE_PREFIX, WSDL_NAMESPACE);
    w.setPrefix(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE);
    w.setPrefix(soapPrefix, soapNamespace);
    if (jmsActive) {
        if (esbSoap) {
            w.setPrefix(SOAP_JMS_NAMESPACE_PREFIX, ESB_SOAP_JMS_NAMESPACE);
            w.setPrefix(ESB_SOAP_JNDI_NAMESPACE_PREFIX, ESB_SOAP_JNDI_NAMESPACE);
        } else {
            w.setPrefix(SOAP_JMS_NAMESPACE_PREFIX, SOAP_JMS_NAMESPACE);
        }
    }
    w.setPrefix(getTargetNamespacePrefix(), getTargetNamespace());
    for (String prefix : namespaceByPrefix.keySet()) {
        w.setPrefix(prefix, namespaceByPrefix.get(prefix));
    }
    w.writeStartElement(WSDL_NAMESPACE, "definitions");
    {
        w.writeNamespace(WSDL_NAMESPACE_PREFIX, WSDL_NAMESPACE);
        w.writeNamespace(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE);
        w.writeNamespace(soapPrefix, soapNamespace);
        if (esbSoap) {
            w.writeNamespace(ESB_SOAP_JNDI_NAMESPACE_PREFIX, ESB_SOAP_JNDI_NAMESPACE);
        }
        w.writeNamespace(getTargetNamespacePrefix(), getTargetNamespace());
        for (String prefix : namespaceByPrefix.keySet()) {
            w.writeNamespace(prefix, namespaceByPrefix.get(prefix));
        }
        w.writeAttribute("targetNamespace", getTargetNamespace());

        documentation(w);
        types(w);
        messages(w);
        portType(w);
        binding(w);
        service(w, servlet);
    }
    w.writeEndDocument();
    warnings(w);
    w.close();
}

From source file:nz.co.jsrsolutions.ds3.test.RetrieveTestData.java

public static void main(String[] args) {

    logger.info("Starting application [ rtd ] ...");

    try {/*from  www  . ja  va  2 s.  c  o  m*/

        config.addConfiguration(
                new XMLConfiguration(RetrieveTestData.class.getClassLoader().getResource(CONFIG_FILENAME)));

        HierarchicalConfiguration appConfig = config.configurationAt(APPLICATION_CONFIG_ROOT);

        EodDataProvider eodDataProvider = null;

        OutputStream out = new FileOutputStream(OUTPUT_FILENAME);
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);

        eodDataProvider = EodDataProviderFactory.create(appConfig, EODDATA_PROVIDER_NAME);

        writer.writeStartDocument("utf-8", "1.0");
        writer.writeCharacters(NEWLINE);
        writer.writeComment("Test data for running DataScraper unit tests against");
        writer.writeCharacters(NEWLINE);

        writer.setPrefix(XML_PREFIX, XML_NAMESPACE_URI);

        writer.writeStartElement(XML_NAMESPACE_URI, TESTDATA_LOCALNAME);
        writer.writeNamespace(XML_PREFIX, XML_NAMESPACE_URI);
        writer.writeCharacters(NEWLINE);

        serializeExchanges(eodDataProvider, writer);
        serializeSymbols(eodDataProvider, writer);
        serializeQuotes(eodDataProvider, writer);

        writer.writeEndElement();
        writer.writeCharacters(NEWLINE);
        writer.writeEndDocument();
        writer.flush();
        writer.close();

    } catch (ConfigurationException ce) {

        logger.error(ce.toString());
        ce.printStackTrace();

    } catch (Exception e) {

        logger.error(e.toString());
        logger.error(e);

    }

    logger.info("Exiting application [ rtd ] ...");

}

From source file:org.activiti.bpmn.converter.export.DefinitionsRootExport.java

@SuppressWarnings("unchecked")
public static void writeRootElement(BpmnModel model, XMLStreamWriter xtw, String encoding) throws Exception {
    xtw.writeStartDocument(encoding, "1.0");

    // start definitions root element
    xtw.writeStartElement(ELEMENT_DEFINITIONS);
    xtw.setDefaultNamespace(BPMN2_NAMESPACE);
    xtw.writeDefaultNamespace(BPMN2_NAMESPACE);
    xtw.writeNamespace(XSI_PREFIX, XSI_NAMESPACE);
    xtw.writeNamespace(XSD_PREFIX, SCHEMA_NAMESPACE);
    xtw.writeNamespace(ACTIVITI_EXTENSIONS_PREFIX, ACTIVITI_EXTENSIONS_NAMESPACE);
    xtw.writeNamespace(BPMNDI_PREFIX, BPMNDI_NAMESPACE);
    xtw.writeNamespace(OMGDC_PREFIX, OMGDC_NAMESPACE);
    xtw.writeNamespace(OMGDI_PREFIX, OMGDI_NAMESPACE);
    for (String prefix : model.getNamespaces().keySet()) {
        if (!defaultNamespaces.contains(prefix) && StringUtils.isNotEmpty(prefix))
            xtw.writeNamespace(prefix, model.getNamespaces().get(prefix));
    }//from  w ww.  j a v  a 2 s. c o m
    xtw.writeAttribute(TYPE_LANGUAGE_ATTRIBUTE, SCHEMA_NAMESPACE);
    xtw.writeAttribute(EXPRESSION_LANGUAGE_ATTRIBUTE, XPATH_NAMESPACE);
    if (StringUtils.isNotEmpty(model.getTargetNamespace())) {
        xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, model.getTargetNamespace());
    } else {
        xtw.writeAttribute(TARGET_NAMESPACE_ATTRIBUTE, PROCESS_NAMESPACE);
    }

    BpmnXMLUtil.writeCustomAttributes(model.getDefinitionsAttributes().values(), xtw, model.getNamespaces(),
            defaultAttributes);
}

From source file:org.activiti.dmn.converter.util.DmnXMLUtil.java

protected static void writeExtensionElement(DmnExtensionElement extensionElement,
        Map<String, String> namespaceMap, XMLStreamWriter xtw) throws Exception {
    if (StringUtils.isNotEmpty(extensionElement.getName())) {
        Map<String, String> localNamespaceMap = new HashMap<String, String>();
        if (StringUtils.isNotEmpty(extensionElement.getNamespace())) {
            if (StringUtils.isNotEmpty(extensionElement.getNamespacePrefix())) {
                xtw.writeStartElement(extensionElement.getNamespacePrefix(), extensionElement.getName(),
                        extensionElement.getNamespace());

                if (namespaceMap.containsKey(extensionElement.getNamespacePrefix()) == false
                        || namespaceMap.get(extensionElement.getNamespacePrefix())
                                .equals(extensionElement.getNamespace()) == false) {

                    xtw.writeNamespace(extensionElement.getNamespacePrefix(), extensionElement.getNamespace());
                    namespaceMap.put(extensionElement.getNamespacePrefix(), extensionElement.getNamespace());
                    localNamespaceMap.put(extensionElement.getNamespacePrefix(),
                            extensionElement.getNamespace());
                }/*  w w  w  .j  a va2  s  . c  om*/
            } else {
                xtw.writeStartElement(extensionElement.getNamespace(), extensionElement.getName());
            }
        } else {
            xtw.writeStartElement(extensionElement.getName());
        }

        for (List<DmnExtensionAttribute> attributes : extensionElement.getAttributes().values()) {
            for (DmnExtensionAttribute attribute : attributes) {
                if (StringUtils.isNotEmpty(attribute.getName()) && attribute.getValue() != null) {
                    if (StringUtils.isNotEmpty(attribute.getNamespace())) {
                        if (StringUtils.isNotEmpty(attribute.getNamespacePrefix())) {

                            if (namespaceMap.containsKey(attribute.getNamespacePrefix()) == false
                                    || namespaceMap.get(attribute.getNamespacePrefix())
                                            .equals(attribute.getNamespace()) == false) {

                                xtw.writeNamespace(attribute.getNamespacePrefix(), attribute.getNamespace());
                                namespaceMap.put(attribute.getNamespacePrefix(), attribute.getNamespace());
                            }

                            xtw.writeAttribute(attribute.getNamespacePrefix(), attribute.getNamespace(),
                                    attribute.getName(), attribute.getValue());
                        } else {
                            xtw.writeAttribute(attribute.getNamespace(), attribute.getName(),
                                    attribute.getValue());
                        }
                    } else {
                        xtw.writeAttribute(attribute.getName(), attribute.getValue());
                    }
                }
            }
        }

        if (extensionElement.getElementText() != null) {
            xtw.writeCharacters(extensionElement.getElementText());
        } else {
            for (List<DmnExtensionElement> childElements : extensionElement.getChildElements().values()) {
                for (DmnExtensionElement childElement : childElements) {
                    writeExtensionElement(childElement, namespaceMap, xtw);
                }
            }
        }

        for (String prefix : localNamespaceMap.keySet()) {
            namespaceMap.remove(prefix);
        }

        xtw.writeEndElement();
    }
}

From source file:org.apache.axiom.om.impl.serialize.StreamingOMSerializer.java

/**
 * @param reader/*from  ww  w.  j a v  a  2  s .com*/
 * @param writer
 * @throws XMLStreamException
 */
protected void serializeElement(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException {

    // Note: To serialize the start tag, we must follow the order dictated by the JSR-173 (StAX) specification.
    // Please keep this code in sync with the code in OMSerializerUtil.serializeStartpart

    // The algorithm is:
    // ... generate writeStartElement
    //
    // ... generate setPrefix/setDefaultNamespace for each namespace declaration if the prefix is unassociated.
    // ... generate setPrefix/setDefaultNamespace if the prefix of the element is unassociated
    // ... generate setPrefix/setDefaultNamespace for each unassociated prefix of the attributes.
    //
    // ... generate writeNamespace/writerDefaultNamespace for the new namespace declarations determine during the "set" processing
    // ... generate writeAttribute for each attribute

    ArrayList writePrefixList = null;
    ArrayList writeNSList = null;

    // Get the prefix and namespace of the element.  "" and null are identical.
    String ePrefix = reader.getPrefix();
    ePrefix = (ePrefix != null && ePrefix.length() == 0) ? null : ePrefix;
    String eNamespace = reader.getNamespaceURI();
    eNamespace = (eNamespace != null && eNamespace.length() == 0) ? null : eNamespace;

    // Write the startElement if required
    if (eNamespace != null) {
        if (ePrefix == null) {
            if (!OMSerializerUtil.isAssociated("", eNamespace, writer)) {

                if (writePrefixList == null) {
                    writePrefixList = new ArrayList();
                    writeNSList = new ArrayList();
                }
                writePrefixList.add("");
                writeNSList.add(eNamespace);
            }

            writer.writeStartElement("", reader.getLocalName(), eNamespace);
        } else {

            if (!OMSerializerUtil.isAssociated(ePrefix, eNamespace, writer)) {
                if (writePrefixList == null) {
                    writePrefixList = new ArrayList();
                    writeNSList = new ArrayList();
                }
                writePrefixList.add(ePrefix);
                writeNSList.add(eNamespace);
            }

            writer.writeStartElement(ePrefix, reader.getLocalName(), eNamespace);
        }
    } else {
        writer.writeStartElement(reader.getLocalName());
    }

    // Generate setPrefix for the namespace declarations
    int count = reader.getNamespaceCount();
    for (int i = 0; i < count; i++) {
        String prefix = reader.getNamespacePrefix(i);
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        String namespace = reader.getNamespaceURI(i);
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;

        String newPrefix = OMSerializerUtil.generateSetPrefix(prefix, namespace, writer, false);
        // If this is a new association, remember it so that it can written out later
        if (newPrefix != null) {
            if (writePrefixList == null) {
                writePrefixList = new ArrayList();
                writeNSList = new ArrayList();
            }
            if (!writePrefixList.contains(newPrefix)) {
                writePrefixList.add(newPrefix);
                writeNSList.add(namespace);
            }
        }
    }

    // Generate setPrefix for the element
    // If the prefix is not associated with a namespace yet, remember it so that we can
    // write out a namespace declaration
    String newPrefix = OMSerializerUtil.generateSetPrefix(ePrefix, eNamespace, writer, false);
    // If this is a new association, remember it so that it can written out later
    if (newPrefix != null) {
        if (writePrefixList == null) {
            writePrefixList = new ArrayList();
            writeNSList = new ArrayList();
        }
        if (!writePrefixList.contains(newPrefix)) {
            writePrefixList.add(newPrefix);
            writeNSList.add(eNamespace);
        }
    }

    // Now Generate setPrefix for each attribute
    count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        String prefix = reader.getAttributePrefix(i);
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        String namespace = reader.getAttributeNamespace(i);
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;

        // Default prefix referencing is not allowed on an attribute
        if (prefix == null && namespace != null) {
            String writerPrefix = writer.getPrefix(namespace);
            writerPrefix = (writerPrefix != null && writerPrefix.length() == 0) ? null : writerPrefix;
            prefix = (writerPrefix != null) ? writerPrefix : generateUniquePrefix(writer.getNamespaceContext());
        }
        newPrefix = OMSerializerUtil.generateSetPrefix(prefix, namespace, writer, true);
        // If the prefix is not associated with a namespace yet, remember it so that we can
        // write out a namespace declaration
        if (newPrefix != null) {
            if (writePrefixList == null) {
                writePrefixList = new ArrayList();
                writeNSList = new ArrayList();
            }
            if (!writePrefixList.contains(newPrefix)) {
                writePrefixList.add(newPrefix);
                writeNSList.add(namespace);
            }
        }
    }

    // Now Generate setPrefix for each prefix referenced in an xsi:type
    // For example xsi:type="p:dataType"
    // The following code will make sure that setPrefix is called for "p".
    count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        String prefix = reader.getAttributePrefix(i);
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        String namespace = reader.getAttributeNamespace(i);
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;
        String localName = reader.getAttributeLocalName(i);

        if (XSI_URI.equals(namespace) && XSI_LOCAL_NAME.equals(localName)) {
            String value = reader.getAttributeValue(i);
            if (DEBUG_ENABLED) {
                log.debug("The value of xsi:type is " + value);
            }
            if (value != null) {
                value = value.trim();
                if (value.indexOf(":") > 0) {
                    String refPrefix = value.substring(0, value.indexOf(":"));
                    String refNamespace = reader.getNamespaceURI(refPrefix);
                    if (refNamespace != null && refNamespace.length() > 0) {

                        newPrefix = OMSerializerUtil.generateSetPrefix(refPrefix, refNamespace, writer, true);
                        // If the prefix is not associated with a namespace yet, remember it so that we can
                        // write out a namespace declaration
                        if (newPrefix != null) {
                            if (DEBUG_ENABLED) {
                                log.debug(
                                        "An xmlns:" + newPrefix + "=\"" + refNamespace + "\" will be written");
                            }
                            if (writePrefixList == null) {
                                writePrefixList = new ArrayList();
                                writeNSList = new ArrayList();
                            }
                            if (!writePrefixList.contains(newPrefix)) {
                                writePrefixList.add(newPrefix);
                                writeNSList.add(refNamespace);
                            }
                        }
                    }

                }
            }
        }
    }

    // Now write out the list of namespace declarations in this list that we constructed
    // while doing the "set" processing.
    if (writePrefixList != null) {
        for (int i = 0; i < writePrefixList.size(); i++) {
            String prefix = (String) writePrefixList.get(i);
            String namespace = (String) writeNSList.get(i);
            if (prefix != null) {
                if (namespace == null) {
                    writer.writeNamespace(prefix, "");
                } else {
                    writer.writeNamespace(prefix, namespace);
                }
            } else {
                writer.writeDefaultNamespace(namespace);
            }
        }
    }

    // Now write the attributes
    count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        String prefix = reader.getAttributePrefix(i);
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        String namespace = reader.getAttributeNamespace(i);
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;

        if (prefix == null && namespace != null) {
            // Default namespaces are not allowed on an attribute reference.
            // Earlier in this code, a unique prefix was added for this case...now obtain and use it
            prefix = writer.getPrefix(namespace);
            //XMLStreamWriter doesn't allow for getPrefix to know whether you're asking for the prefix
            //for an attribute or an element. So if the namespace matches the default namespace getPrefix will return
            //the empty string, as if it were an element, in all cases (even for attributes, and even if 
            //there was a prefix specifically set up for this), which is not the desired behavior.
            //Since the interface is base java, we can't fix it where we need to (by adding an attr boolean to 
            //XMLStreamWriter.getPrefix), so we hack it in here...
            if (prefix == null || "".equals(prefix)) {
                for (int j = 0; j < writePrefixList.size(); j++) {
                    if (namespace.equals((String) writeNSList.get(j))) {
                        prefix = (String) writePrefixList.get(j);
                    }
                }
            }
        } else if (namespace != null && !prefix.equals("xml")) {
            // Use the writer's prefix if it is different, but if the writers 
            // prefix is empty then do not replace because attributes do not
            // default to the default namespace like elements do.
            String writerPrefix = writer.getPrefix(namespace);
            if (!prefix.equals(writerPrefix) && !"".equals(writerPrefix)) {
                prefix = writerPrefix;
            }
        }
        if (namespace != null) {
            // Qualified attribute
            writer.writeAttribute(prefix, namespace, reader.getAttributeLocalName(i),
                    reader.getAttributeValue(i));
        } else {
            // Unqualified attribute
            writer.writeAttribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i));
        }
    }
}