Example usage for javax.xml.stream XMLStreamReader getAttributeValue

List of usage examples for javax.xml.stream XMLStreamReader getAttributeValue

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader getAttributeValue.

Prototype

public String getAttributeValue(int index);

Source Link

Document

Returns the value of the attribute at the index

Usage

From source file:org.apache.solr.handler.loader.XMLLoader.java

/**
 * @since solr 1.2/*w  w w .  j  a  v a2 s  .com*/
 */
void processUpdate(SolrQueryRequest req, UpdateRequestProcessor processor, XMLStreamReader parser)
        throws XMLStreamException, IOException, FactoryConfigurationError {
    AddUpdateCommand addCmd = null;
    SolrParams params = req.getParams();
    while (true) {
        int event = parser.next();
        switch (event) {
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            return;

        case XMLStreamConstants.START_ELEMENT:
            String currTag = parser.getLocalName();
            if (currTag.equals(UpdateRequestHandler.ADD)) {
                log.trace("SolrCore.update(add)");

                addCmd = new AddUpdateCommand(req);

                // First look for commitWithin parameter on the request, will be overwritten for individual <add>'s
                addCmd.commitWithin = params.getInt(UpdateParams.COMMIT_WITHIN, -1);
                addCmd.overwrite = params.getBool(UpdateParams.OVERWRITE, true);

                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    if (UpdateRequestHandler.OVERWRITE.equals(attrName)) {
                        addCmd.overwrite = StrUtils.parseBoolean(attrVal);
                    } else if (UpdateRequestHandler.COMMIT_WITHIN.equals(attrName)) {
                        addCmd.commitWithin = Integer.parseInt(attrVal);
                    } else {
                        log.warn("XML element <add> has invalid XML attr: " + attrName);
                    }
                }

            } else if ("doc".equals(currTag)) {
                if (addCmd != null) {
                    log.trace("adding doc...");
                    addCmd.clear();
                    addCmd.solrDoc = readDoc(parser);
                    processor.processAdd(addCmd);
                } else {
                    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                            "Unexpected <doc> tag without an <add> tag surrounding it.");
                }
            } else if (UpdateRequestHandler.COMMIT.equals(currTag)
                    || UpdateRequestHandler.OPTIMIZE.equals(currTag)) {
                log.trace("parsing " + currTag);

                CommitUpdateCommand cmd = new CommitUpdateCommand(req,
                        UpdateRequestHandler.OPTIMIZE.equals(currTag));
                ModifiableSolrParams mp = new ModifiableSolrParams();

                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    mp.set(attrName, attrVal);
                }

                RequestHandlerUtils.validateCommitParams(mp);
                SolrParams p = SolrParams.wrapDefaults(mp, req.getParams()); // default to the normal request params for commit options
                RequestHandlerUtils.updateCommit(cmd, p);

                processor.processCommit(cmd);
            } // end commit
            else if (UpdateRequestHandler.ROLLBACK.equals(currTag)) {
                log.trace("parsing rollback");

                RollbackUpdateCommand cmd = new RollbackUpdateCommand(req);

                processor.processRollback(cmd);
            } // end rollback
            else if (UpdateRequestHandler.DELETE.equals(currTag)) {
                log.trace("parsing delete");
                processDelete(req, processor, parser);
            } // end delete
            break;
        }
    }
}

From source file:org.apache.solr.handler.loader.XMLLoader.java

/**
 * @since solr 1.3/*from  w  ww.jav  a  2  s  .c om*/
 */
void processDelete(SolrQueryRequest req, UpdateRequestProcessor processor, XMLStreamReader parser)
        throws XMLStreamException, IOException {
    // Parse the command
    DeleteUpdateCommand deleteCmd = new DeleteUpdateCommand(req);

    // First look for commitWithin parameter on the request, will be overwritten for individual <delete>'s
    SolrParams params = req.getParams();
    deleteCmd.commitWithin = params.getInt(UpdateParams.COMMIT_WITHIN, -1);

    for (int i = 0; i < parser.getAttributeCount(); i++) {
        String attrName = parser.getAttributeLocalName(i);
        String attrVal = parser.getAttributeValue(i);
        if ("fromPending".equals(attrName)) {
            // deprecated
        } else if ("fromCommitted".equals(attrName)) {
            // deprecated
        } else if (UpdateRequestHandler.COMMIT_WITHIN.equals(attrName)) {
            deleteCmd.commitWithin = Integer.parseInt(attrVal);
        } else {
            log.warn("XML element <delete> has invalid XML attr: " + attrName);
        }
    }

    StringBuilder text = new StringBuilder();
    while (true) {
        int event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            String mode = parser.getLocalName();
            if (!("id".equals(mode) || "query".equals(mode))) {
                String msg = "XML element <delete> has invalid XML child element: " + mode;
                log.warn(msg);
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, msg);
            }
            text.setLength(0);

            if ("id".equals(mode)) {
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    if (UpdateRequestHandler.VERSION.equals(attrName)) {
                        deleteCmd.setVersion(Long.parseLong(attrVal));
                    }
                    if (UpdateRequest.ROUTE.equals(attrName)) {
                        deleteCmd.setRoute(attrVal);
                    }
                }
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            String currTag = parser.getLocalName();
            if ("id".equals(currTag)) {
                deleteCmd.setId(text.toString());
            } else if ("query".equals(currTag)) {
                deleteCmd.setQuery(text.toString());
            } else if ("delete".equals(currTag)) {
                return;
            } else {
                String msg = "XML element <delete> has invalid XML (closing) child element: " + currTag;
                log.warn(msg);
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, msg);
            }
            processor.processDelete(deleteCmd);
            deleteCmd.clear();
            break;

        // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            text.append(parser.getText());
            break;
        }
    }
}

From source file:org.apache.solr.handler.loader.XMLLoader.java

/**
 * Given the input stream, read a document
 *
 * @since solr 1.3//from ww w .j ava 2 s . c  o m
 */
public SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException {
    SolrInputDocument doc = new SolrInputDocument();

    String attrName = "";
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        attrName = parser.getAttributeLocalName(i);
        if ("boost".equals(attrName)) {
            doc.setDocumentBoost(Float.parseFloat(parser.getAttributeValue(i)));
        } else {
            log.warn("XML element <doc> has invalid XML attr:" + attrName);
        }
    }

    StringBuilder text = new StringBuilder();
    String name = null;
    float boost = 1.0f;
    boolean isNull = false;
    String update = null;
    Collection<SolrInputDocument> subDocs = null;
    Map<String, Map<String, Object>> updateMap = null;
    boolean complete = false;
    while (!complete) {
        int event = parser.next();
        switch (event) {
        // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            text.append(parser.getText());
            break;

        case XMLStreamConstants.END_ELEMENT:
            if ("doc".equals(parser.getLocalName())) {
                if (subDocs != null && !subDocs.isEmpty()) {
                    doc.addChildDocuments(subDocs);
                    subDocs = null;
                }
                complete = true;
                break;
            } else if ("field".equals(parser.getLocalName())) {
                // should I warn in some text has been found too
                Object v = isNull ? null : text.toString();
                if (update != null) {
                    if (updateMap == null)
                        updateMap = new HashMap<>();
                    Map<String, Object> extendedValues = updateMap.get(name);
                    if (extendedValues == null) {
                        extendedValues = new HashMap<>(1);
                        updateMap.put(name, extendedValues);
                    }
                    Object val = extendedValues.get(update);
                    if (val == null) {
                        extendedValues.put(update, v);
                    } else {
                        // multiple val are present
                        if (val instanceof List) {
                            List list = (List) val;
                            list.add(v);
                        } else {
                            List<Object> values = new ArrayList<>();
                            values.add(val);
                            values.add(v);
                            extendedValues.put(update, values);
                        }
                    }
                    break;
                }
                doc.addField(name, v, boost);
                boost = 1.0f;
                // field is over
                name = null;
            }
            break;

        case XMLStreamConstants.START_ELEMENT:
            text.setLength(0);
            String localName = parser.getLocalName();
            if ("doc".equals(localName)) {
                if (subDocs == null)
                    subDocs = Lists.newArrayList();
                subDocs.add(readDoc(parser));
            } else {
                if (!"field".equals(localName)) {
                    String msg = "XML element <doc> has invalid XML child element: " + localName;
                    log.warn(msg);
                    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, msg);
                }
                boost = 1.0f;
                update = null;
                isNull = false;
                String attrVal = "";
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    attrName = parser.getAttributeLocalName(i);
                    attrVal = parser.getAttributeValue(i);
                    if (NAME.equals(attrName)) {
                        name = attrVal;
                    } else if ("boost".equals(attrName)) {
                        boost = Float.parseFloat(attrVal);
                    } else if ("null".equals(attrName)) {
                        isNull = StrUtils.parseBoolean(attrVal);
                    } else if ("update".equals(attrName)) {
                        update = attrVal;
                    } else {
                        log.warn("XML element <field> has invalid XML attr: " + attrName);
                    }
                }
            }
            break;
        }
    }

    if (updateMap != null) {
        for (Map.Entry<String, Map<String, Object>> entry : updateMap.entrySet()) {
            name = entry.getKey();
            Map<String, Object> value = entry.getValue();
            doc.addField(name, value, 1.0f);
        }
    }

    return doc;
}

From source file:org.apache.solr.handler.XMLLoader.java

/**
 * @since solr 1.2/*  w ww. java2s  . c  om*/
 */
void processUpdate(SolrQueryRequest req, UpdateRequestProcessor processor, XMLStreamReader parser)
        throws XMLStreamException, IOException, FactoryConfigurationError, InstantiationException,
        IllegalAccessException, TransformerConfigurationException {
    AddUpdateCommand addCmd = null;
    // Need to instansiate a SolrParams, even if req is null, for backward compat with legacyUpdate
    SolrParams params = (req != null) ? req.getParams() : new ModifiableSolrParams();
    while (true) {
        int event = parser.next();
        switch (event) {
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            return;

        case XMLStreamConstants.START_ELEMENT:
            String currTag = parser.getLocalName();
            if (currTag.equals(XmlUpdateRequestHandler.ADD)) {
                XmlUpdateRequestHandler.log.trace("SolrCore.update(add)");

                addCmd = new AddUpdateCommand();

                // First look for commitWithin parameter on the request, will be overwritten for individual <add>'s
                addCmd.commitWithin = params.getInt(UpdateParams.COMMIT_WITHIN, -1);

                boolean overwrite = true; // the default

                Boolean overwritePending = null;
                Boolean overwriteCommitted = null;
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    if (XmlUpdateRequestHandler.OVERWRITE.equals(attrName)) {
                        overwrite = StrUtils.parseBoolean(attrVal);
                    } else if (XmlUpdateRequestHandler.ALLOW_DUPS.equals(attrName)) {
                        overwrite = !StrUtils.parseBoolean(attrVal);
                    } else if (XmlUpdateRequestHandler.COMMIT_WITHIN.equals(attrName)) {
                        addCmd.commitWithin = Integer.parseInt(attrVal);
                    } else if (XmlUpdateRequestHandler.OVERWRITE_PENDING.equals(attrName)) {
                        overwritePending = StrUtils.parseBoolean(attrVal);
                    } else if (XmlUpdateRequestHandler.OVERWRITE_COMMITTED.equals(attrName)) {
                        overwriteCommitted = StrUtils.parseBoolean(attrVal);
                    } else {
                        XmlUpdateRequestHandler.log.warn("Unknown attribute id in add:" + attrName);
                    }
                }

                // check if these flags are set
                if (overwritePending != null && overwriteCommitted != null) {
                    if (overwritePending != overwriteCommitted) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                                "can't have different values for 'overwritePending' and 'overwriteCommitted'");
                    }
                    overwrite = overwritePending;
                }
                addCmd.overwriteCommitted = overwrite;
                addCmd.overwritePending = overwrite;
                addCmd.allowDups = !overwrite;
            } else if ("doc".equals(currTag)) {
                //            if(addCmd != null) {
                XmlUpdateRequestHandler.log.trace("adding doc...");
                addCmd.clear();
                addCmd.solrDoc = readDoc(parser);
                processor.processAdd(addCmd);
                //            } else {
                //              throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unexpected <doc> tag without an <add> tag surrounding it.");
                //            }
            } else if (XmlUpdateRequestHandler.COMMIT.equals(currTag)
                    || XmlUpdateRequestHandler.OPTIMIZE.equals(currTag)) {
                XmlUpdateRequestHandler.log.trace("parsing " + currTag);

                CommitUpdateCommand cmd = new CommitUpdateCommand(
                        XmlUpdateRequestHandler.OPTIMIZE.equals(currTag));

                boolean sawWaitSearcher = false, sawWaitFlush = false;
                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    if (XmlUpdateRequestHandler.WAIT_FLUSH.equals(attrName)) {
                        cmd.waitFlush = StrUtils.parseBoolean(attrVal);
                        sawWaitFlush = true;
                    } else if (XmlUpdateRequestHandler.WAIT_SEARCHER.equals(attrName)) {
                        cmd.waitSearcher = StrUtils.parseBoolean(attrVal);
                        sawWaitSearcher = true;
                    } else if (UpdateParams.MAX_OPTIMIZE_SEGMENTS.equals(attrName)) {
                        cmd.maxOptimizeSegments = Integer.parseInt(attrVal);
                    } else if (UpdateParams.EXPUNGE_DELETES.equals(attrName)) {
                        cmd.expungeDeletes = StrUtils.parseBoolean(attrVal);
                    } else {
                        XmlUpdateRequestHandler.log.warn("unexpected attribute commit/@" + attrName);
                    }
                }

                // If waitFlush is specified and waitSearcher wasn't, then
                // clear waitSearcher.
                if (sawWaitFlush && !sawWaitSearcher) {
                    cmd.waitSearcher = false;
                }
                processor.processCommit(cmd);
            } // end commit
            else if (XmlUpdateRequestHandler.ROLLBACK.equals(currTag)) {
                XmlUpdateRequestHandler.log.trace("parsing " + currTag);

                RollbackUpdateCommand cmd = new RollbackUpdateCommand();

                processor.processRollback(cmd);
            } // end rollback
            else if (XmlUpdateRequestHandler.DELETE.equals(currTag)) {
                XmlUpdateRequestHandler.log.trace("parsing delete");
                processDelete(processor, parser);
            } // end delete
            break;
        }
    }
}

From source file:org.apache.solr.handler.XMLLoader.java

/**
 * @since solr 1.3/*from   w ww  . j av a  2 s  . c  o  m*/
 */
void processDelete(UpdateRequestProcessor processor, XMLStreamReader parser)
        throws XMLStreamException, IOException {
    // Parse the command
    DeleteUpdateCommand deleteCmd = new DeleteUpdateCommand();
    deleteCmd.fromPending = true;
    deleteCmd.fromCommitted = true;
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        String attrName = parser.getAttributeLocalName(i);
        String attrVal = parser.getAttributeValue(i);
        if ("fromPending".equals(attrName)) {
            deleteCmd.fromPending = StrUtils.parseBoolean(attrVal);
        } else if ("fromCommitted".equals(attrName)) {
            deleteCmd.fromCommitted = StrUtils.parseBoolean(attrVal);
        } else {
            XmlUpdateRequestHandler.log.warn("unexpected attribute delete/@" + attrName);
        }
    }

    StringBuilder text = new StringBuilder();
    while (true) {
        int event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            String mode = parser.getLocalName();
            if (!("id".equals(mode) || "query".equals(mode))) {
                XmlUpdateRequestHandler.log.warn("unexpected XML tag /delete/" + mode);
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "unexpected XML tag /delete/" + mode);
            }
            text.setLength(0);
            break;

        case XMLStreamConstants.END_ELEMENT:
            String currTag = parser.getLocalName();
            if ("id".equals(currTag)) {
                deleteCmd.id = text.toString();
            } else if ("query".equals(currTag)) {
                deleteCmd.query = text.toString();
            } else if ("delete".equals(currTag)) {
                return;
            } else {
                XmlUpdateRequestHandler.log.warn("unexpected XML tag /delete/" + currTag);
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "unexpected XML tag /delete/" + currTag);
            }
            processor.processDelete(deleteCmd);
            deleteCmd.id = null;
            deleteCmd.query = null;
            break;

        // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            text.append(parser.getText());
            break;
        }
    }
}

From source file:org.apache.solr.handler.XMLLoader.java

/**
 * Given the input stream, read a document
 *
 * @since solr 1.3/*from w  ww.j  a  va2 s .c  o  m*/
 */
SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException {
    SolrInputDocument doc = new SolrInputDocument();

    String attrName = "";
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        attrName = parser.getAttributeLocalName(i);
        if ("boost".equals(attrName)) {
            doc.setDocumentBoost(Float.parseFloat(parser.getAttributeValue(i)));
        } else {
            XmlUpdateRequestHandler.log.warn("Unknown attribute doc/@" + attrName);
        }
    }

    StringBuilder text = new StringBuilder();
    String name = null;
    float boost = 1.0f;
    boolean isNull = false;
    while (true) {
        int event = parser.next();
        switch (event) {
        // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            text.append(parser.getText());
            break;

        case XMLStreamConstants.END_ELEMENT:
            if ("doc".equals(parser.getLocalName())) {
                return doc;
            } else if ("field".equals(parser.getLocalName())) {
                if (!isNull) {
                    doc.addField(name, text.toString(), boost);
                    boost = 1.0f;
                }
            }
            break;

        case XMLStreamConstants.START_ELEMENT:
            text.setLength(0);
            String localName = parser.getLocalName();
            if (!"field".equals(localName)) {
                XmlUpdateRequestHandler.log.warn("unexpected XML tag doc/" + localName);
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "unexpected XML tag doc/" + localName);
            }
            boost = 1.0f;
            String attrVal = "";
            for (int i = 0; i < parser.getAttributeCount(); i++) {
                attrName = parser.getAttributeLocalName(i);
                attrVal = parser.getAttributeValue(i);
                if ("name".equals(attrName)) {
                    name = attrVal;
                } else if ("boost".equals(attrName)) {
                    boost = Float.parseFloat(attrVal);
                } else if ("null".equals(attrName)) {
                    isNull = StrUtils.parseBoolean(attrVal);
                } else {
                    XmlUpdateRequestHandler.log.warn("Unknown attribute doc/field/@" + attrName);
                }
            }
            break;
        }
    }
}

From source file:org.apache.synapse.commons.json.JsonDataSource.java

public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException {
    XMLStreamReader reader = getReader();
    xmlWriter.writeStartDocument();/*from  ww w  . java 2  s . c o  m*/
    while (reader.hasNext()) {
        int x = reader.next();
        switch (x) {
        case XMLStreamConstants.START_ELEMENT:
            xmlWriter.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader.getNamespaceURI());
            int namespaceCount = reader.getNamespaceCount();
            for (int i = namespaceCount - 1; i >= 0; i--) {
                xmlWriter.writeNamespace(reader.getNamespacePrefix(i), reader.getNamespaceURI(i));
            }
            int attributeCount = reader.getAttributeCount();
            for (int i = 0; i < attributeCount; i++) {
                xmlWriter.writeAttribute(reader.getAttributePrefix(i), reader.getAttributeNamespace(i),
                        reader.getAttributeLocalName(i), reader.getAttributeValue(i));
            }
            break;
        case XMLStreamConstants.START_DOCUMENT:
            break;
        case XMLStreamConstants.CHARACTERS:
            xmlWriter.writeCharacters(reader.getText());
            break;
        case XMLStreamConstants.CDATA:
            xmlWriter.writeCData(reader.getText());
            break;
        case XMLStreamConstants.END_ELEMENT:
            xmlWriter.writeEndElement();
            break;
        case XMLStreamConstants.END_DOCUMENT:
            xmlWriter.writeEndDocument();
            break;
        case XMLStreamConstants.SPACE:
            break;
        case XMLStreamConstants.COMMENT:
            xmlWriter.writeComment(reader.getText());
            break;
        case XMLStreamConstants.DTD:
            xmlWriter.writeDTD(reader.getText());
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            xmlWriter.writeProcessingInstruction(reader.getPITarget(), reader.getPIData());
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            xmlWriter.writeEntityRef(reader.getLocalName());
            break;
        default:
            throw new OMException();
        }
    }
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
    xmlWriter.close();
}

From source file:org.apache.syncope.client.cli.commands.migrate.MigrateConf.java

private static void copyAttrs(final XMLStreamReader streamReader, final XMLStreamWriter streamWriter,
        final String... but) throws XMLStreamException {

    Set<String> exceptions = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
    exceptions.addAll(Arrays.asList(but));
    exceptions.add("id");
    exceptions.add("name");

    for (int i = 0; i < streamReader.getAttributeCount(); i++) {
        String name = streamReader.getAttributeLocalName(i);
        if (!exceptions.contains(name)) {
            streamWriter.writeAttribute(name, streamReader.getAttributeValue(i));
        }// www. j  av a2 s .  co  m
    }
}

From source file:org.apache.syncope.client.cli.commands.migrate.MigrateConf.java

private static String getAttributeValue(final XMLStreamReader streamReader, final String key) {
    String value = null;/*from   w  w  w  . ja  va2 s  .c om*/

    for (int i = 0; i < streamReader.getAttributeCount(); i++) {
        String attrName = streamReader.getAttributeLocalName(i);
        if (attrName.equalsIgnoreCase(key)) {
            value = streamReader.getAttributeValue(i);
        }
    }

    return value;
}

From source file:org.deegree.client.core.renderer.OutputXMLRenderer.java

private void encodeXML(ResponseWriter writer, String value) throws IOException {
    int depth = 0;
    try {//from w  ww .  ja  v  a  2 s  .c  o  m
        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(value));
        boolean lastWasEndElement = false;
        boolean lastWasComment = false;
        while (reader.hasNext()) {
            switch (reader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                if (!lastWasComment) {
                    writer.startElement("br", null);
                    writer.endElement("br");
                }
                writer.write(getSpaces(depth));
                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&lt;");
                writer.endElement("span");

                writer.startElement("span", null);
                writer.writeAttribute("class", "tag", null);
                String prefix = reader.getPrefix();
                writer.write(
                        (prefix != null && prefix.length() > 0 ? prefix + ":" : "") + reader.getLocalName());
                writer.endElement("span");

                for (int i = 0; i < reader.getAttributeCount(); i++) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", "attributeName", null);
                    writer.write("&#160;");
                    String attributePrefix = reader.getAttributePrefix(i);
                    writer.write(
                            (attributePrefix != null && attributePrefix.length() > 0 ? attributePrefix + ":"
                                    : "") + reader.getAttributeLocalName(i));
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("=\"");
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "text", null);
                    writer.write(encodeString(reader.getAttributeValue(i)));
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("\"");
                    writer.endElement("span");
                }

                for (int i = 0; i < reader.getNamespaceCount(); i++) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", "attributeName", null);
                    writer.write("&#160;");
                    String nsPrefix = reader.getNamespacePrefix(i);
                    writer.write("xmlns");
                    if (nsPrefix != null && !nsPrefix.isEmpty()) {
                        writer.write(":" + nsPrefix);
                    }
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("=\"");
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "text", null);
                    writer.write(reader.getNamespaceURI(i));
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("\"");
                    writer.endElement("span");
                }

                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&gt;");
                writer.endElement("span");
                depth++;
                lastWasEndElement = false;
                lastWasComment = false;
                break;
            case XMLStreamConstants.CHARACTERS:
                String text = reader.getText();
                if (text.trim().length() > 0) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", "text", null);
                    writer.write(encodeString(text));
                    writer.endElement("span");
                    lastWasEndElement = false;
                    lastWasComment = false;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                depth--;
                if (lastWasEndElement) {
                    writer.startElement("br", null);
                    writer.endElement("br");
                    writer.write(getSpaces(depth));
                }
                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&lt;/");
                writer.endElement("span");

                writer.startElement("span", null);
                writer.writeAttribute("class", "tag", null);
                prefix = reader.getPrefix();
                writer.write(
                        (prefix != null && prefix.length() > 0 ? prefix + ":" : "") + reader.getLocalName());
                writer.endElement("span");

                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&gt;");
                writer.endElement("span");
                lastWasEndElement = true;
                lastWasComment = false;
                break;
            case XMLStreamConstants.COMMENT:
                writer.startElement("div", null);
                writer.writeAttribute("class", "comment", null);
                writer.write("&lt;/!--" + reader.getText() + "--&gt;");
                writer.endElement("div");
                lastWasEndElement = false;
                lastWasComment = true;
                break;
            default:
                break;
            }
            reader.next();

        }
        reader.close();
    } catch (Throwable e) {
        if (depth == 0) {
            writer.writeText("Response could not parsed as XML.", null);
        } else {
            writer.writeText("... (if you want the complete document, please click the download button)", null);
        }
    }
}