Example usage for javax.xml.stream XMLStreamConstants START_DOCUMENT

List of usage examples for javax.xml.stream XMLStreamConstants START_DOCUMENT

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamConstants START_DOCUMENT.

Prototype

int START_DOCUMENT

To view the source code for javax.xml.stream XMLStreamConstants START_DOCUMENT.

Click Source Link

Document

Indicates an event is a start document

Usage

From source file:org.mule.module.xml.util.XMLUtils.java

public static void copy(XMLStreamReader reader, XMLStreamWriter writer, boolean fragment)
        throws XMLStreamException {
    // number of elements read in
    int read = 0;
    int event = reader.getEventType();

    while (reader.hasNext()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            read++;//from   www  .  j  a v a  2s .  c  o m
            writeStartElement(reader, writer);
            break;
        case XMLStreamConstants.END_ELEMENT:
            writer.writeEndElement();
            read--;
            if (read <= 0 && !fragment) {
                return;
            }
            break;
        case XMLStreamConstants.CHARACTERS:
            writer.writeCharacters(reader.getText());
            break;
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.END_DOCUMENT:
        case XMLStreamConstants.ATTRIBUTE:
        case XMLStreamConstants.NAMESPACE:
            break;
        default:
            break;
        }
        event = reader.next();
    }
}

From source file:org.openvpms.tools.data.loader.DataLoader.java

/**
 * Loads data from a stream.//  w  w  w . j a  v a 2  s  .  com
 *
 * @param reader the stream reader
 * @param path   a path representing the stream source, for logging purposes
 * @throws XMLStreamException for any stream error
 */
public void load(XMLStreamReader reader, String path) throws XMLStreamException {

    Stack<LoadState> stack = new Stack<LoadState>();
    for (int event = reader.next(); event != XMLStreamConstants.END_DOCUMENT; event = reader.next()) {
        LoadState current;
        switch (event) {
        case XMLStreamConstants.START_DOCUMENT:
            break;
        case XMLStreamConstants.START_ELEMENT:
            String elementName = reader.getLocalName();
            if ("data".equals(elementName)) {
                startData(reader, stack, path);
            } else if (!"archetype".equals(elementName)) {
                throw new ArchetypeDataLoaderException(ErrorInStartElement);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (!stack.isEmpty()) {
                current = stack.pop();
                load(current);
            }

            if (verbose) {
                log.info("[END PROCESSING element=" + reader.getLocalName() + "]");
            }
            break;

        default:
            break;
        }
    }
}

From source file:org.pentaho.di.trans.steps.webservices.WebService.java

private void compatibleProcessRows(InputStream anXml, Object[] rowData, RowMetaInterface rowMeta,
        boolean ignoreNamespacePrefix, String encoding) throws KettleException {

    // First we should get the complete string
    // The problem is that the string can contain XML or any other format such as HTML saying the service is no longer
    // available.
    // We're talking about a WEB service here.
    // As such, to keep the original parsing scheme, we first read the content.
    // Then we create an input stream from the content again.
    // It's elaborate, but that way we can report on the failure more correctly.
    ////ww w  .j  a  v  a  2 s  . c  om
    String response = readStringFromInputStream(anXml, encoding);

    // Create a new reader to feed into the XML Input Factory below...
    //
    StringReader stringReader = new StringReader(response.toString());

    // TODO Very empirical : see if we can do something better here
    try {
        XMLInputFactory vFactory = XMLInputFactory.newInstance();
        XMLStreamReader vReader = vFactory.createXMLStreamReader(stringReader);

        Object[] outputRowData = RowDataUtil.allocateRowData(data.outputRowMeta.size());
        int outputIndex = 0;

        boolean processing = false;
        boolean oneValueRowProcessing = false;
        for (int event = vReader.next(); vReader.hasNext(); event = vReader.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:

                // Start new code
                // START_ELEMENT= 1
                //
                if (log.isRowLevel()) {
                    logRowlevel("START_ELEMENT / " + vReader.getAttributeCount() + " / "
                            + vReader.getNamespaceCount());
                }

                // If we start the xml element named like the return type,
                // we start a new row
                //
                if (log.isRowLevel()) {
                    logRowlevel("vReader.getLocalName = " + vReader.getLocalName());
                }
                if (Const.isEmpty(meta.getOutFieldArgumentName())) {
                    // getOutFieldArgumentName() == null
                    if (oneValueRowProcessing) {
                        WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(),
                                ignoreNamespacePrefix);
                        if (field != null) {
                            outputRowData[outputIndex++] = getValue(vReader.getElementText(), field);
                            putRow(data.outputRowMeta, outputRowData);
                            oneValueRowProcessing = false;
                        } else {
                            if (meta.getOutFieldContainerName().equals(vReader.getLocalName())) {
                                // meta.getOutFieldContainerName() = vReader.getLocalName()
                                if (log.isRowLevel()) {
                                    logRowlevel("OutFieldContainerName = " + meta.getOutFieldContainerName());
                                }
                                oneValueRowProcessing = true;
                            }
                        }
                    }
                } else {
                    // getOutFieldArgumentName() != null
                    if (log.isRowLevel()) {
                        logRowlevel("OutFieldArgumentName = " + meta.getOutFieldArgumentName());
                    }
                    if (meta.getOutFieldArgumentName().equals(vReader.getLocalName())) {
                        if (log.isRowLevel()) {
                            logRowlevel("vReader.getLocalName = " + vReader.getLocalName());
                        }
                        if (log.isRowLevel()) {
                            logRowlevel("OutFieldArgumentName = ");
                        }
                        if (processing) {
                            WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(),
                                    ignoreNamespacePrefix);
                            if (field != null) {
                                int index = data.outputRowMeta.indexOfValue(field.getName());
                                if (index >= 0) {
                                    outputRowData[index] = getValue(vReader.getElementText(), field);
                                }
                            }
                            processing = false;
                        } else {
                            WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(),
                                    ignoreNamespacePrefix);
                            if (meta.getFieldsOut().size() == 1 && field != null) {
                                // This can be either a simple return element, or a complex type...
                                //
                                try {
                                    if (meta.isPassingInputData()) {
                                        for (int i = 0; i < rowMeta.getValueMetaList().size(); i++) {
                                            ValueMetaInterface valueMeta = getInputRowMeta().getValueMeta(i);
                                            outputRowData[outputIndex++] = valueMeta.cloneValueData(rowData[i]);

                                        }
                                    }

                                    outputRowData[outputIndex++] = getValue(vReader.getElementText(), field);
                                    putRow(data.outputRowMeta, outputRowData);
                                } catch (WstxParsingException e) {
                                    throw new KettleStepException("Unable to get value for field ["
                                            + field.getName()
                                            + "].  Verify that this is not a complex data type by looking at the response XML.",
                                            e);
                                }
                            } else {
                                for (WebServiceField curField : meta.getFieldsOut()) {
                                    if (!Const.isEmpty(curField.getName())) {
                                        outputRowData[outputIndex++] = getValue(vReader.getElementText(),
                                                curField);
                                    }
                                }
                                processing = true;
                            }
                        }

                    } else {
                        if (log.isRowLevel()) {
                            logRowlevel("vReader.getLocalName = " + vReader.getLocalName());
                        }
                        if (log.isRowLevel()) {
                            logRowlevel("OutFieldArgumentName = " + meta.getOutFieldArgumentName());
                        }
                    }
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                // END_ELEMENT= 2
                if (log.isRowLevel()) {
                    logRowlevel("END_ELEMENT");
                }
                // If we end the xml element named as the return type, we
                // finish a row
                if ((meta.getOutFieldArgumentName() == null
                        && meta.getOperationName().equals(vReader.getLocalName()))) {
                    oneValueRowProcessing = false;
                } else if (meta.getOutFieldArgumentName() != null
                        && meta.getOutFieldArgumentName().equals(vReader.getLocalName())) {
                    putRow(data.outputRowMeta, outputRowData);
                    processing = false;
                }
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                // PROCESSING_INSTRUCTION= 3
                if (log.isRowLevel()) {
                    logRowlevel("PROCESSING_INSTRUCTION");
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                // CHARACTERS= 4
                if (log.isRowLevel()) {
                    logRowlevel("CHARACTERS");
                }
                break;
            case XMLStreamConstants.COMMENT:
                // COMMENT= 5
                if (log.isRowLevel()) {
                    logRowlevel("COMMENT");
                }
                break;
            case XMLStreamConstants.SPACE:
                // PROCESSING_INSTRUCTION= 6
                if (log.isRowLevel()) {
                    logRowlevel("PROCESSING_INSTRUCTION");
                }
                break;
            case XMLStreamConstants.START_DOCUMENT:
                // START_DOCUMENT= 7
                if (log.isRowLevel()) {
                    logRowlevel("START_DOCUMENT");
                }
                if (log.isRowLevel()) {
                    logRowlevel(vReader.getText());
                }
                break;
            case XMLStreamConstants.END_DOCUMENT:
                // END_DOCUMENT= 8
                if (log.isRowLevel()) {
                    logRowlevel("END_DOCUMENT");
                }
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                // ENTITY_REFERENCE= 9
                if (log.isRowLevel()) {
                    logRowlevel("ENTITY_REFERENCE");
                }
                break;
            case XMLStreamConstants.ATTRIBUTE:
                // ATTRIBUTE= 10
                if (log.isRowLevel()) {
                    logRowlevel("ATTRIBUTE");
                }
                break;
            case XMLStreamConstants.DTD:
                // DTD= 11
                if (log.isRowLevel()) {
                    logRowlevel("DTD");
                }
                break;
            case XMLStreamConstants.CDATA:
                // CDATA= 12
                if (log.isRowLevel()) {
                    logRowlevel("CDATA");
                }
                break;
            case XMLStreamConstants.NAMESPACE:
                // NAMESPACE= 13
                if (log.isRowLevel()) {
                    logRowlevel("NAMESPACE");
                }
                break;
            case XMLStreamConstants.NOTATION_DECLARATION:
                // NOTATION_DECLARATION= 14
                if (log.isRowLevel()) {
                    logRowlevel("NOTATION_DECLARATION");
                }
                break;
            case XMLStreamConstants.ENTITY_DECLARATION:
                // ENTITY_DECLARATION= 15
                if (log.isRowLevel()) {
                    logRowlevel("ENTITY_DECLARATION");
                }
                break;
            default:
                break;
            }
        }
    } catch (Exception e) {
        throw new KettleStepException(
                BaseMessages.getString(PKG, "WebServices.ERROR0010.OutputParsingError", response.toString()),
                e);
    }
}

From source file:org.pentaho.di.trans.steps.xmlinputstream.XMLInputStream.java

private Object[] processEvent() throws KettleException {

    Object[] outputRowData = RowDataUtil.allocateRowData(data.outputRowMeta.size());
    XMLEvent e = null;/*w  ww.j  av  a  2s. c  o m*/
    try {
        e = data.xmlEventReader.nextEvent();
    } catch (XMLStreamException ex) {
        throw new KettleException(ex);
    }

    int eventType = e.getEventType();
    if (data.pos_xml_data_type_numeric != -1) {
        outputRowData[data.pos_xml_data_type_numeric] = new Long(eventType);
    }
    if (data.pos_xml_data_type_description != -1) {
        if (eventType == 0 || eventType > eventDescription.length) {
            // unknown eventType
            outputRowData[data.pos_xml_data_type_description] = eventDescription[0] + "(" + eventType + ")";
        } else {
            outputRowData[data.pos_xml_data_type_description] = eventDescription[eventType];
        }
    }
    if (data.pos_xml_location_line != -1) {
        outputRowData[data.pos_xml_location_line] = new Long(e.getLocation().getLineNumber());
    }
    if (data.pos_xml_location_column != -1) {
        outputRowData[data.pos_xml_location_column] = new Long(e.getLocation().getColumnNumber());
    }

    switch (eventType) {

    case XMLStreamConstants.START_ELEMENT:
        data.elementLevel++;
        if (data.elementLevel > PARENT_ID_ALLOCATE_SIZE - 1) {
            throw new KettleException(BaseMessages.getString(PKG, "XMLInputStream.Log.TooManyNestedElements",
                    PARENT_ID_ALLOCATE_SIZE));
        }
        if (data.elementParentID[data.elementLevel] == null) {
            data.elementParentID[data.elementLevel] = data.elementID;
        }
        data.elementID++;
        data.elementLevelID[data.elementLevel] = data.elementID;

        String xml_data_name;
        if (meta.isEnableNamespaces()) {
            String prefix = e.asStartElement().getName().getPrefix();
            if (Utils.isEmpty(prefix)) {
                xml_data_name = e.asStartElement().getName().getLocalPart();
            } else { // add namespace prefix:
                xml_data_name = prefix + ":" + e.asStartElement().getName().getLocalPart();
            }
        } else {
            xml_data_name = e.asStartElement().getName().getLocalPart();
        }
        if (data.pos_xml_data_name >= 0) {
            outputRowData[data.pos_xml_data_name] = xml_data_name;
        }
        // store the name
        data.elementName[data.elementLevel] = xml_data_name;
        // store simple path
        data.elementPath[data.elementLevel] = data.elementPath[data.elementLevel - 1] + "/" + xml_data_name;

        // write Namespaces out
        if (meta.isEnableNamespaces()) {
            outputRowData = parseNamespaces(outputRowData, e);
        }

        // write Attributes out
        outputRowData = parseAttributes(outputRowData, e);

        break;

    case XMLStreamConstants.END_ELEMENT:
        parseEndElement(outputRowData, e.asEndElement());
        putRowOut(outputRowData);
        data.elementParentID[data.elementLevel + 1] = null;
        data.elementLevel--;
        outputRowData = null; // continue
        break;

    case XMLStreamConstants.SPACE:
        outputRowData = null; // ignore & continue
        break;

    case XMLStreamConstants.CHARACTERS:
    case XMLStreamConstants.CDATA:
        if (data.pos_xml_data_name >= 0) {
            outputRowData[data.pos_xml_data_name] = data.elementName[data.elementLevel];
        }
        String xml_data_value = e.asCharacters().getData();
        if (data.pos_xml_data_value >= 0) {
            if (meta.isEnableTrim()) {
                // optional trim is also eliminating white spaces, tab, cr, lf
                xml_data_value = Const.trim(xml_data_value);
            }
            outputRowData[data.pos_xml_data_value] = xml_data_value;
        }

        if (data.pos_xml_data_value < 0 || Utils.isEmpty((String) outputRowData[data.pos_xml_data_value])) {
            outputRowData = null; // ignore & continue
        }
        break;

    case XMLStreamConstants.PROCESSING_INSTRUCTION:
        outputRowData = null; // ignore & continue
        // TODO test if possible
        break;

    case XMLStreamConstants.COMMENT:
        outputRowData = null; // ignore & continue
        // TODO test if possible
        break;

    case XMLStreamConstants.ENTITY_REFERENCE:
        // should be resolved by default
        outputRowData = null; // ignore & continue
        break;

    case XMLStreamConstants.START_DOCUMENT:
        // just get this information out
        break;

    case XMLStreamConstants.END_DOCUMENT:
        // just get this information out
        break;

    default:
        logBasic("Event:" + eventType);
        outputRowData = null; // ignore & continue
    }

    return outputRowData;
}

From source file:org.rhq.plugins.hadoop.HadoopServerConfigurationDelegate.java

private static void updateFile(File configFile, Map<String, PropertySimple> allProps)
        throws IOException, InterruptedException, XMLStreamException {
    InputStream in = null;/*from w w w.  jav  a2s . co  m*/
    XMLStreamReader rdr = null;

    OutputStream out = null;
    XMLStreamWriter outWrt = null;

    try {
        Set<String> processedPropertyNames = new HashSet<String>();

        in = new BufferedInputStream(new FileInputStream(configFile));
        rdr = XML_INPUT_FACTORY.createXMLStreamReader(in);

        File tmpFile = File.createTempFile("hadoop-plugin", null);
        out = new FileOutputStream(tmpFile);
        outWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);

        ByteArrayOutputStream stash = new ByteArrayOutputStream();
        XMLStreamWriter stashWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(stash);
        boolean outputActive = true;

        outWrt.writeStartDocument();

        while (rdr.hasNext()) {
            int event = rdr.next();

            XMLStreamWriter wrt = outputActive ? outWrt : stashWrt;

            switch (event) {
            case XMLStreamConstants.ATTRIBUTE:
                break;
            case XMLStreamConstants.CDATA:
                wrt.writeCData(rdr.getText());
                break;
            case XMLStreamConstants.CHARACTERS:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.COMMENT:
                wrt.writeComment(rdr.getText());
                break;
            case XMLStreamConstants.DTD:
                wrt.writeDTD(rdr.getText());
                break;
            case XMLStreamConstants.END_DOCUMENT:
                wrt.writeEndDocument();
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    String encoding = rdr.getEncoding();
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }

                    String propertyTagSoFar = Charset.forName(encoding)
                            .decode(ByteBuffer.wrap(stash.toByteArray())).toString();
                    DetectedPropertyNameAndUpdatedTag propAndTag = updateProperty(propertyTagSoFar, allProps);

                    //yes, we're intentionally circumventing the xml stream writer, because we already have the XML data we want to write.
                    outWrt.flush();
                    out.write(propAndTag.updatedTag.getBytes("UTF-8"));

                    processedPropertyNames.add(propAndTag.propertyName);

                    //reset stuff
                    stash.reset();
                    wrt = outWrt;
                    outputActive = true;
                } else if (CONFIGURATION_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    //now add the new props
                    for (String prop : processedPropertyNames) {
                        allProps.remove(prop);
                    }

                    for (Map.Entry<String, PropertySimple> e : allProps.entrySet()) {
                        outWrt.writeStartElement(PROPERTY_TAG_NAME);

                        outWrt.writeStartElement(NAME_TAG_NAME);
                        outWrt.writeCharacters(e.getKey());
                        outWrt.writeEndElement();

                        outWrt.writeStartElement(VALUE_TAG_NAME);
                        outWrt.writeCharacters(e.getValue().getStringValue());
                        outWrt.writeEndElement();

                        outWrt.writeEndElement();
                    }
                }
                wrt.writeEndElement();
                break;
            case XMLStreamConstants.ENTITY_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                wrt.writeEntityRef(rdr.getText());
                break;
            case XMLStreamConstants.NAMESPACE:
                for (int i = 0; i < rdr.getNamespaceCount(); ++i) {
                    wrt.writeNamespace(rdr.getNamespacePrefix(i), rdr.getNamespaceURI(i));
                }
                break;
            case XMLStreamConstants.NOTATION_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                wrt.writeProcessingInstruction(rdr.getPITarget(), rdr.getPIData());
                break;
            case XMLStreamConstants.SPACE:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.START_DOCUMENT:
                //this seems to be never called for some strange reason
                //wrt.writeStartDocument();
                break;
            case XMLStreamConstants.START_ELEMENT:
                wrt.writeStartElement(rdr.getName().getPrefix(), rdr.getName().getLocalPart(),
                        rdr.getName().getNamespaceURI());

                for (int i = 0; i < rdr.getAttributeCount(); ++i) {
                    wrt.writeAttribute(rdr.getAttributePrefix(i), rdr.getAttributeNamespace(i),
                            rdr.getAttributeLocalName(i), rdr.getAttributeValue(i));
                }

                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    wrt.writeCharacters("");
                    outputActive = false;
                }
                break;
            }
        }

        outWrt.flush();
        out.flush();
        out.close();

        in.close();

        //now copy the temp file in the place of the original one
        FileUtil.copyFile(tmpFile, configFile);
    } finally {
        rdr.close();

        outWrt.flush();
        outWrt.close();

        try {
            in.close();
        } finally {
            out.flush();
            out.close();
        }
    }
}

From source file:org.slc.sli.api.resources.config.StAXMsgBodyReader.java

/**
 * Helper method for digesting XML documents
 * @param reader XML reader/*from  w w  w  .  ja  va 2s.  c o  m*/
 * @return EntityBody representation that corresponds to the xml
 * @throws XMLStreamException on malformed XML
 */
private static final EntityBody readDocument(final XMLStreamReader reader) throws XMLStreamException {
    if (XMLStreamConstants.START_DOCUMENT == reader.getEventType()) {
        EntityBody body = null;
        while (reader.hasNext()) {
            reader.next();
            switch (reader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT: {
                body = readDocumentElement(reader);
                return body;
            }
            case XMLStreamConstants.END_DOCUMENT: {
                return body;
            }
            case XMLStreamConstants.CHARACTERS: {
                // Ignore
                break;
            }
            default: {
                throw new XMLStreamException();
            }
            }
        }
    } else {
        throw new XMLStreamException(reader.getLocalName());
    }
    throw new XMLStreamException();
}

From source file:org.slc.sli.modeling.wadl.reader.WadlReader.java

private static final Application readDocument(final XMLStreamReader reader) {
    try {/*from www .j  a  v  a  2  s .  c  o m*/
        if (XMLStreamConstants.START_DOCUMENT == reader.getEventType()) {
            Application app = null;
            while (reader.hasNext()) {
                reader.next();
                switch (reader.getEventType()) {
                case XMLStreamConstants.START_ELEMENT: {
                    if (match(WadlElementName.APPLICATION, reader)) {
                        app = readApplication(reader);
                        if (app == null) {
                            throw new IllegalStateException();
                        }
                        break;
                    } else {
                        throw new AssertionError(reader.getLocalName());
                    }
                }
                case XMLStreamConstants.END_DOCUMENT: {
                    if (app == null) {
                        throw new IllegalStateException();
                    }
                    return app;
                }
                default: {
                    throw new AssertionError(reader.getEventType());
                }
                }
            }
            throw new AssertionError();
        } else {
            throw new AssertionError(reader.getLocalName());
        }
    } catch (final XMLStreamException e) {
        throw new WadlRuntimeException(e);
    }
}

From source file:org.slc.sli.modeling.xmi.comp.XmiMappingReader.java

private static final void assertStartDocument(final XMLStreamReader reader) {
    if (XMLStreamConstants.START_DOCUMENT != reader.getEventType()) {
        throw new AssertionError(reader.getLocalName());
    }//from ww  w. j  av  a2 s  . com
}

From source file:org.slc.sli.modeling.xmi.reader.XmiReader.java

protected static final Model readDocument(final XMLStreamReader reader) {
    try {/*  www.  j  a va 2 s.  c o m*/
        if (XMLStreamConstants.START_DOCUMENT == reader.getEventType()) {
            Model model = null;
            while (reader.hasNext()) {
                reader.next();
                switch (reader.getEventType()) {
                case XMLStreamConstants.START_ELEMENT: {
                    if ("XMI".equals(reader.getLocalName())) {
                        model = readXMI(reader);
                        if (model == null) {
                            throw new IllegalStateException();
                        }
                        break;
                    } else {
                        throw new XmiRuntimeException("Expecting Foo element, got: " + reader.getLocalName());
                    }
                }
                case XMLStreamConstants.END_DOCUMENT: {
                    if (model == null) {
                        throw new IllegalStateException();
                    }
                    return model;
                }
                default: {
                    throw new AssertionError(reader.getEventType());
                }
                }
            }
            throw new AssertionError();
        } else {
            throw new AssertionError(reader.getLocalName());
        }
    } catch (final XMLStreamException e) {
        throw new XmiRuntimeException(e);
    }
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

private String saxFilter(Node node) {
    try {//from   w w  w.  j  a  va  2  s .co m
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        final StringWriter w1 = new StringWriter();
        transformer.transform(new DOMSource(node), new StreamResult(w1));
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLEventReader eventReader = xif
                .createXMLEventReader(new StreamSource(new StringReader(w1.toString())));
        XMLEventReader filteredReader = xif.createFilteredReader(eventReader, new EventFilter() {
            @Override
            public boolean accept(XMLEvent event) {
                int type = event.getEventType();
                if (type == XMLStreamConstants.START_DOCUMENT || type == XMLStreamConstants.END_DOCUMENT) {
                    return false;
                }
                if (event.isStartElement()) {
                    StartElement startElement = (StartElement) event;
                    QName name = startElement.getName();
                    if ("".equals(name.getNamespaceURI()) && "root".equals(name.getLocalPart())) {
                        return false;
                    }
                }
                if (event.isEndElement()) {
                    EndElement endElement = (EndElement) event;
                    QName name = endElement.getName();
                    if ("".equals(name.getNamespaceURI()) && "root".equals(name.getLocalPart())) {
                        return false;
                    }
                }
                return true;
            }
        });
        StringWriter sw = new StringWriter();
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLEventWriter writer = xof.createXMLEventWriter(sw);
        while (filteredReader.hasNext()) {
            writer.add(filteredReader.nextEvent());
        }
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}