Example usage for javax.xml.stream XMLStreamWriter writeAttribute

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

Introduction

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

Prototype


public void writeAttribute(String prefix, String namespaceURI, String localName, String value)
        throws XMLStreamException;

Source Link

Document

Writes an attribute to the output stream

Usage

From source file:Main.java

/**
 * Borrowed from org.apache.xml.security.test.stax.utils.XmlReaderToWriter
 *///from  ww  w  .ja  va 2s  .c o m
public static void write(XMLStreamReader xmlr, XMLStreamWriter writer) throws XMLStreamException {
    switch (xmlr.getEventType()) {
    case XMLEvent.START_ELEMENT:
        final String localName = xmlr.getLocalName();
        final String namespaceURI = xmlr.getNamespaceURI();
        if (namespaceURI != null && namespaceURI.length() > 0) {
            final String prefix = xmlr.getPrefix();
            if (prefix != null) {
                writer.writeStartElement(prefix, localName, namespaceURI);
            } else {
                writer.writeStartElement(namespaceURI, localName);
            }
        } else {
            writer.writeStartElement(localName);
        }

        for (int i = 0, len = xmlr.getNamespaceCount(); i < len; i++) {
            String prefix = xmlr.getNamespacePrefix(i);
            if (prefix == null) {
                writer.writeDefaultNamespace(xmlr.getNamespaceURI(i));
            } else {
                writer.writeNamespace(prefix, xmlr.getNamespaceURI(i));
            }
        }

        for (int i = 0, len = xmlr.getAttributeCount(); i < len; i++) {
            final String attUri = xmlr.getAttributeNamespace(i);

            if (attUri != null && attUri.length() > 0) {
                final String prefix = xmlr.getAttributePrefix(i);
                if (prefix != null) {
                    writer.writeAttribute(prefix, attUri, xmlr.getAttributeLocalName(i),
                            xmlr.getAttributeValue(i));
                } else {
                    writer.writeAttribute(attUri, xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
                }
            } else {
                writer.writeAttribute(xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
            }

        }
        break;
    case XMLEvent.END_ELEMENT:
        writer.writeEndElement();
        break;
    case XMLEvent.SPACE:
    case XMLEvent.CHARACTERS:
        char[] text = new char[xmlr.getTextLength()];
        xmlr.getTextCharacters(0, text, 0, xmlr.getTextLength());
        writer.writeCharacters(text, 0, text.length);
        break;
    case XMLEvent.PROCESSING_INSTRUCTION:
        writer.writeProcessingInstruction(xmlr.getPITarget(), xmlr.getPIData());
        break;
    case XMLEvent.CDATA:
        writer.writeCData(xmlr.getText());
        break;
    case XMLEvent.COMMENT:
        writer.writeComment(xmlr.getText());
        break;
    case XMLEvent.ENTITY_REFERENCE:
        writer.writeEntityRef(xmlr.getLocalName());
        break;
    case XMLEvent.START_DOCUMENT:
        String encoding = xmlr.getCharacterEncodingScheme();
        String version = xmlr.getVersion();

        if (encoding != null && version != null) {
            writer.writeStartDocument(encoding, version);
        } else if (version != null) {
            writer.writeStartDocument(xmlr.getVersion());
        }
        break;
    case XMLEvent.END_DOCUMENT:
        writer.writeEndDocument();
        break;
    case XMLEvent.DTD:
        writer.writeDTD(xmlr.getText());
        break;
    }
}

From source file:microsoft.exchange.webservices.data.core.EwsServiceXmlWriter.java

/**
 * @param element DOM element/*from   www. j  a  v  a2 s. c  om*/
 * @param writer XML stream writer
 * @throws XMLStreamException the XML stream exception
 */
public static void addElement(Element element, XMLStreamWriter writer) throws XMLStreamException {
    String nameSpace = element.getNamespaceURI();
    String prefix = element.getPrefix();
    String localName = element.getLocalName();
    if (prefix == null) {
        prefix = "";
    }
    if (localName == null) {
        localName = element.getNodeName();

        if (localName == null) {
            throw new IllegalStateException("Element's local name cannot be null!");
        }
    }

    String decUri = writer.getNamespaceContext().getNamespaceURI(prefix);
    boolean declareNamespace = decUri == null || !decUri.equals(nameSpace);

    if (nameSpace == null || nameSpace.length() == 0) {
        writer.writeStartElement(localName);
    } else {
        writer.writeStartElement(prefix, localName, nameSpace);
    }

    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);

        String name = attr.getNodeName();
        String attrPrefix = "";
        int prefixIndex = name.indexOf(':');
        if (prefixIndex != -1) {
            attrPrefix = name.substring(0, prefixIndex);
            name = name.substring(prefixIndex + 1);
        }

        if ("xmlns".equals(attrPrefix)) {
            writer.writeNamespace(name, attr.getNodeValue());
            if (name.equals(prefix) && attr.getNodeValue().equals(nameSpace)) {
                declareNamespace = false;
            }
        } else {
            if ("xmlns".equals(name) && "".equals(attrPrefix)) {
                writer.writeNamespace("", attr.getNodeValue());
                if (attr.getNodeValue().equals(nameSpace)) {
                    declareNamespace = false;
                }
            } else {
                writer.writeAttribute(attrPrefix, attr.getNamespaceURI(), name, attr.getNodeValue());
            }
        }
    }

    if (declareNamespace) {
        if (nameSpace == null) {
            writer.writeNamespace(prefix, "");
        } else {
            writer.writeNamespace(prefix, nameSpace);
        }
    }

    NodeList nodes = element.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        writeNode(n, writer);
    }

    writer.writeEndElement();

}

From source file:org.activiti.bpmn.converter.SequenceFlowXMLConverter.java

@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
        throws Exception {
    SequenceFlow sequenceFlow = (SequenceFlow) element;

    if (StringUtils.isNotEmpty(sequenceFlow.getConditionExpression())) {
        xtw.writeStartElement(ELEMENT_FLOW_CONDITION);
        xtw.writeAttribute(XSI_PREFIX, XSI_NAMESPACE, "type", "tFormalExpression");
        xtw.writeCData(sequenceFlow.getConditionExpression());
        xtw.writeEndElement();//from  w  ww  . j  a  v a  2s. co m
    }
}

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

public static void writeQualifiedAttribute(String attributeName, String value, XMLStreamWriter xtw)
        throws Exception {
    if (StringUtils.isNotEmpty(value)) {
        xtw.writeAttribute(ACTIVITI_EXTENSIONS_PREFIX, ACTIVITI_EXTENSIONS_NAMESPACE, attributeName, value);
    }/*from  w  ww  .  j  a  va2  s.  c  o  m*/
}

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());
                }//from  www. j a va2 s  . c  o m
            } 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   w  ww . ja v a2s  .c o  m*/
 * @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));
        }
    }
}

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

/**
 * @param reader//from   w  w w  .j ava  2s .  c  o m
 * @param writer
 * @throws XMLStreamException
 */
protected void serializeAttributes(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException {
    int count = reader.getAttributeCount();
    String prefix = null;
    String namespaceName = null;
    String writerPrefix = null;
    for (int i = 0; i < count; i++) {
        prefix = reader.getAttributePrefix(i);
        namespaceName = reader.getAttributeNamespace(i);
        /*
           Some parser implementations return null for the unqualified namespace.
           But getPrefix(null) will throw an exception (according to the XMLStreamWriter
           javadoc. We guard against this by using "" for the unqualified namespace. 
        */
        namespaceName = (namespaceName == null) ? "" : namespaceName;

        // Using getNamespaceContext should be avoided when not necessary.
        // Some parser implementations construct a new NamespaceContext each time it is invoked.
        // writerPrefix = writer.getNamespaceContext().getPrefix(namespaceName);
        writerPrefix = writer.getPrefix(namespaceName);

        if (!"".equals(namespaceName)) {
            //prefix has already being declared but this particular attrib has a
            //no prefix attached. So use the prefix provided by the writer
            if (writerPrefix != null && (prefix == null || prefix.equals(""))) {
                writer.writeAttribute(writerPrefix, namespaceName, reader.getAttributeLocalName(i),
                        reader.getAttributeValue(i));

                //writer prefix is available but different from the current
                //prefix of the attrib. We should be decalring the new prefix
                //as a namespace declaration
            } else if (prefix != null && !"".equals(prefix) && !prefix.equals(writerPrefix)) {
                writer.writeNamespace(prefix, namespaceName);
                writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i),
                        reader.getAttributeValue(i));

                //prefix is null (or empty), but the namespace name is valid! it has not
                //being written previously also. So we need to generate a prefix
                //here
            } else {
                prefix = generateUniquePrefix(writer.getNamespaceContext());
                writer.writeNamespace(prefix, namespaceName);
                writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i),
                        reader.getAttributeValue(i));
            }
        } else {
            //empty namespace is equal to no namespace!
            writer.writeAttribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i));
        }

    }
}

From source file:org.apache.axiom.om.impl.util.OMSerializerUtil.java

/**
 * Method serializeAttribute.//from  w  w w. ja  v a  2 s .c  o m
 *
 * @param attr
 * @param writer
 * @throws XMLStreamException
 * @deprecated use serializeStartpart instead
 */
public static void serializeAttribute(OMAttribute attr, XMLStreamWriter writer) throws XMLStreamException {

    // first check whether the attribute is associated with a namespace
    OMNamespace ns = attr.getNamespace();
    String prefix = null;
    String namespaceName = null;
    if (ns != null) {

        // add the prefix if it's availble
        prefix = ns.getPrefix();
        namespaceName = ns.getNamespaceURI();
        if (prefix != null) {
            writer.writeAttribute(prefix, namespaceName, attr.getLocalName(), attr.getAttributeValue());
        } else {
            writer.writeAttribute(namespaceName, attr.getLocalName(), attr.getAttributeValue());
        }
    } else {
        String localName = attr.getLocalName();
        String attributeValue = attr.getAttributeValue();
        writer.writeAttribute(localName, attributeValue);
    }
}

From source file:org.apache.axiom.om.impl.util.OMSerializerUtil.java

/**
 * Method serializeStartpart. Serialize the start tag of an element.
 *
 * @param element//  w  w w.j a v a  2 s.c o  m
 * @param localName (in some cases, the caller wants to force a different localName)
 * @param writer
 * @throws XMLStreamException
 */
public static void serializeStartpart(OMElement element, String localName, 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 StreamingOMSerializer.serializeElement

    // 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 namespace and prefix of the element
    OMNamespace eOMNamespace = element.getNamespace();
    String ePrefix = null;
    String eNamespace = null;
    if (eOMNamespace != null) {
        ePrefix = eOMNamespace.getPrefix();
        eNamespace = eOMNamespace.getNamespaceURI();
    }
    ePrefix = (ePrefix != null && ePrefix.length() == 0) ? null : ePrefix;
    eNamespace = (eNamespace != null && eNamespace.length() == 0) ? null : eNamespace;

    if (eNamespace != null) {
        if (ePrefix == null) {
            if (!isAssociated("", eNamespace, writer)) {
                if (writePrefixList == null) {
                    writePrefixList = new ArrayList();
                    writeNSList = new ArrayList();
                }
                if (!writePrefixList.contains("")) {
                    writePrefixList.add("");
                    writeNSList.add(eNamespace);
                }
            }
            writer.writeStartElement("", localName, eNamespace);
        } else {
            /*
             * If XMLStreamWriter.writeStartElement(prefix,localName,namespaceURI) associates
             * the prefix with the namespace .. 
             */
            if (!isAssociated(ePrefix, eNamespace, writer)) {
                if (writePrefixList == null) {
                    writePrefixList = new ArrayList();
                    writeNSList = new ArrayList();
                }
                if (!writePrefixList.contains(ePrefix)) {
                    writePrefixList.add(ePrefix);
                    writeNSList.add(eNamespace);
                }
            }

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

    // Generate setPrefix for the namespace declarations
    Iterator it = element.getAllDeclaredNamespaces();
    while (it != null && it.hasNext()) {
        OMNamespace omNamespace = (OMNamespace) it.next();
        String prefix = null;
        String namespace = null;
        if (omNamespace != null) {
            prefix = omNamespace.getPrefix();
            namespace = omNamespace.getNamespaceURI();
        }
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;

        String newPrefix = 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
    // Get the prefix and namespace of the element.  "" and null are identical.
    String newPrefix = 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
    Iterator attrs = element.getAllAttributes();
    while (attrs != null && attrs.hasNext()) {
        OMAttribute attr = (OMAttribute) attrs.next();
        OMNamespace omNamespace = attr.getNamespace();
        String prefix = null;
        String namespace = null;
        if (omNamespace != null) {
            prefix = omNamespace.getPrefix();
            namespace = omNamespace.getNamespaceURI();
        }
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        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 : getNextNSPrefix();
        }
        newPrefix = 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".
    attrs = element.getAllAttributes();
    while (attrs != null && attrs.hasNext()) {
        OMAttribute attr = (OMAttribute) attrs.next();
        OMNamespace omNamespace = attr.getNamespace();
        String prefix = null;
        String namespace = null;
        if (omNamespace != null) {
            prefix = omNamespace.getPrefix();
            namespace = omNamespace.getNamespaceURI();
        }
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;
        String local = attr.getLocalName();

        if (XSI_URI.equals(namespace) && XSI_LOCAL_NAME.equals(local)) {
            String value = attr.getAttributeValue();
            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(":"));
                    OMNamespace omNS = element.findNamespaceURI(refPrefix);
                    String refNamespace = (omNS == null) ? null : omNS.getNamespaceURI();
                    if (refNamespace != null && refNamespace.length() > 0) {

                        newPrefix = 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
    attrs = element.getAllAttributes();
    while (attrs != null && attrs.hasNext()) {
        OMAttribute attr = (OMAttribute) attrs.next();
        OMNamespace omNamespace = attr.getNamespace();
        String prefix = null;
        String namespace = null;
        if (omNamespace != null) {
            prefix = omNamespace.getPrefix();
            namespace = omNamespace.getNamespaceURI();
        }
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        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 i = 0; i < writePrefixList.size(); i++) {
                    if (namespace.equals((String) writeNSList.get(i))) {
                        prefix = (String) writePrefixList.get(i);
                    }
                }
            }
        } else if (namespace != null) {
            // 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) && writerPrefix != null && !"".equals(writerPrefix)) {
                prefix = writerPrefix;
            }
        }
        if (namespace != null) {
            if (prefix == null && OMConstants.XMLNS_URI.equals(namespace)) {
                prefix = OMConstants.XMLNS_PREFIX;
            }
            // Qualified attribute
            writer.writeAttribute(prefix, namespace, attr.getLocalName(), attr.getAttributeValue());
        } else {
            // Unqualified attribute
            writer.writeAttribute(attr.getLocalName(), attr.getAttributeValue());
        }
    }
}

From source file:org.apache.axis2.policy.model.MTOM10Assertion.java

public void serialize(XMLStreamWriter writer) throws XMLStreamException {
    String prefix = writer.getPrefix(NS);

    if (prefix == null) {
        prefix = PREFIX;//w  ww . j a v a  2s . co m
        writer.setPrefix(PREFIX, NS);
    }

    writer.writeStartElement(PREFIX, MTOM_SERIALIZATION_CONFIG_LN, NS);

    if (optional) {
        writer.writeAttribute(Constants.ATTR_WSP, null, Constants.Q_ELEM_OPTIONAL_ATTR.getLocalPart(), "true");
    }

    writer.writeNamespace(PREFIX, NS);
    writer.writeEndElement();

}