Example usage for javax.xml.stream XMLStreamReader getAttributeCount

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

Introduction

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

Prototype

public int getAttributeCount();

Source Link

Document

Returns the count of attributes on this START_ELEMENT, this method is only valid on a START_ELEMENT or ATTRIBUTE.

Usage

From source file:Main.java

/**
 * Borrowed from org.apache.xml.security.test.stax.utils.XmlReaderToWriter
 *//*from  ww  w.  j  av  a  2 s.co  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:com.flexive.chemistry.webdav.TextDocumentResource.java

/**
 * Set the value of a property, stream points to the start of the property tag.
 *
 * @param parser    the XML parser// w w  w .jav a  2s  . com
 * @throws XMLStreamException   on parsing errors
 */
protected void processProperty(XMLStreamReader parser) throws XMLStreamException {
    int level = 0;
    String name = null;
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        if ("name".equals(parser.getAttributeName(i).getLocalPart())) {
            name = parser.getAttributeValue(i);
            break;
        }
    }
    if (name == null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("property without name attribute encountered");
        }
        return;
    }

    String value = null;
    for (int event = parser.nextTag(); event != XMLStreamConstants.END_DOCUMENT
            && level >= 0; event = parser.nextTag()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            if ("value".equals(parser.getLocalName())) {
                value = parser.getElementText().trim();
            } else if ("name".equals(parser.getLocalName())) {
                name = parser.getElementText();
            } else {
                level++;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            level--;
            break;
        }
    }

    if (value != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Setting field " + name + " to " + value);
        }
        try {
            object.setValue(name, value);
        } catch (Exception e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Failed to set field " + name + " (ignored): " + e.getMessage());
            }
        }
    }
}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Reads the properties of an entity from the stream into a map of property names to
 * typed values. Reads the entity data as an AtomPub Entry Resource from the specified {@link XMLStreamReader} into
 * a map of <code>String</code> property names to {@link EntityProperty} data typed values.
 * /*from w w  w .j ava2s. c o m*/
 * @param xmlr
 *            The <code>XMLStreamReader</code> to read the data from.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @return
 *         A <code>java.util.HashMap</code> containing a map of <code>String</code> property names to
 *         {@link EntityProperty} data typed values found in the entity data.
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws ParseException
 *             if an error occurs converting the input to a particular data type.
 */
protected static HashMap<String, EntityProperty> readProperties(final XMLStreamReader xmlr,
        final OperationContext opContext) throws XMLStreamException, ParseException {
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.PROPERTIES);
    final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();

    while (xmlr.hasNext()) {
        eventType = xmlr.next();
        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        if (eventType == XMLStreamConstants.START_ELEMENT
                && xmlr.getNamespaceURI().equals(ODataConstants.DATA_SERVICES_NS)) {
            final String key = xmlr.getLocalName();
            String val = Constants.EMPTY_STRING;
            String edmType = null;

            if (xmlr.getAttributeCount() > 0) {
                edmType = xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE);
            }

            // move to chars
            eventType = xmlr.next();

            if (eventType == XMLStreamConstants.CHARACTERS) {
                val = xmlr.getText();

                // end element
                eventType = xmlr.next();
            }

            xmlr.require(XMLStreamConstants.END_ELEMENT, null, key);

            final EntityProperty newProp = new EntityProperty(val, EdmType.parse(edmType));
            properties.put(key, newProp);
        } else if (eventType == XMLStreamConstants.END_ELEMENT && xmlr.getName().toString()
                .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
            // End read properties
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.PROPERTIES);
    return properties;
}

From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java

private void parseElement(Map<String, Object> result, XMLStreamReader reader) {
    int attrCount = reader.getAttributeCount();
    for (int i = 0; i < attrCount; i++) {
        String name = reader.getAttributeLocalName(i);
        String val = reader.getAttributeValue(i);
        putMapValue(result, name, val);
    }/*from   ww  w.  j  a  va 2s .c o m*/
}

From source file:hudson.plugins.report.jck.parsers.JtregReportParser.java

private String findAttributeValue(XMLStreamReader in, String name) {
    int count = in.getAttributeCount();
    for (int i = 0; i < count; i++) {
        if (name.equals(in.getAttributeLocalName(i))) {
            return in.getAttributeValue(i);
        }/* www  . j a v a2  s  .  co m*/
    }
    return null;
}

From source file:at.lame.hellonzb.parser.NzbParser.java

/**
 * This private method is used to create a new instance of DownloadFileSegment.
 * /*from   w  w w. j  a v  a  2 s  . c  o m*/
 * @param parser The parser object to query (XMLStreamReader)
 * @param file The current DownloadFile object
 * @return The new DownloadFileSegment object
 */
private DownloadFileSegment newDownloadFileSegment(XMLStreamReader parser, DownloadFile file) {
    long bytes = 0;
    int index = 0;

    for (int i = 0; i < parser.getAttributeCount(); i++) {
        String attName = parser.getAttributeLocalName(i).toLowerCase();
        if (attName.equals("bytes"))
            bytes = Long.parseLong(parser.getAttributeValue(i));
        else if (attName.equals("number"))
            index = Integer.parseInt(parser.getAttributeValue(i));
    }

    return new DownloadFileSegment(file, bytes, index, file.getGroups());
}

From source file:at.lame.hellonzb.parser.NzbParser.java

/**
 * This private method is used to create a new instance of DownloadFile.
 * /*from  www .ja  v a2s .c om*/
 * @param parser The parser object to query (XMLStreamReader)
 * @return The new DownloadFile object
 */
private DownloadFile newDownloadFile(XMLStreamReader parser) {
    String poster = "";
    String date = "";
    String subject = "";

    for (int i = 0; i < parser.getAttributeCount(); i++) {
        String attName = parser.getAttributeLocalName(i).toLowerCase();
        if (attName.equals("poster"))
            poster = parser.getAttributeValue(i);
        else if (attName.equals("date"))
            date = parser.getAttributeValue(i);
        else if (attName.equals("subject"))
            subject = parser.getAttributeValue(i);
    }

    return new DownloadFile(poster, date, subject, HelloNzbToolkit.getLastFilename(name));
}

From source file:lux.index.XmlPathMapper.java

@Override
public void handleEvent(XMLStreamReader reader, int eventType) {
    if (eventType == START_ELEMENT) {
        getEventQName(currentQName, reader);
        // qnameStack.add(qname);
        currentPath.append(' ');
        currentPath.append(currentQName);
        incrCount(eltQNameCounts, currentQName);
        incrCount(pathCounts, currentPath);
        int len = currentPath.length();
        for (int i = 0; i < reader.getAttributeCount(); i++) {
            getEventAttQName(currentQName, reader, i);
            incrCount(attQNameCounts, currentQName);
            currentPath.append(" @").append(currentQName);
            incrCount(pathCounts, currentPath);
            currentPath.setLength(len);// w w w.  jav a 2s  .  co m
        }
    } else if (eventType == END_ELEMENT) {
        getEventQName(currentQName, reader);
        // snip off the last path step, including its '/' separator char
        currentPath.setLength(currentPath.length() - currentQName.length() - 1);
    } else if (eventType == START_DOCUMENT) {
        currentPath.append("{}");
    }
}

From source file:davmail.exchange.dav.ExchangeDavMethod.java

protected void handleProperty(XMLStreamReader reader, MultiStatusResponse multiStatusResponse)
        throws XMLStreamException {
    while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, "prop")) {
        reader.next();/*from w  w w. j  a v a 2 s  . c  o  m*/
        if (XMLStreamUtil.isStartTag(reader)) {
            Namespace namespace = Namespace.getNamespace(reader.getNamespaceURI());
            String tagLocalName = reader.getLocalName();
            if (reader.getAttributeCount() > 0 && "mv.string".equals(reader.getAttributeValue(0))) {
                handleMultiValuedProperty(reader, multiStatusResponse);
            } else {
                String tagContent = getTagContent(reader);
                if (tagContent != null) {
                    multiStatusResponse.add(new DefaultDavProperty(tagLocalName, tagContent, namespace));
                }
            }
        }
    }
}

From source file:com.tamingtext.tagrecommender.ExtractStackOverflowData.java

/** Extract as many as <code>limit</code> questions from the <code>reader</code>
 *  provided, writing them to <code>writer</code>.
 * @param reader//from w  w  w . j av a 2 s  .c  o  m
 * @param writer
 * @param limit
 * @return
 * @throws XMLStreamException
 */
protected int extractXMLData(XMLStreamReader reader, XMLStreamWriter writer, int limit)
        throws XMLStreamException {

    int questionCount = 0;
    int attrCount;
    boolean copyElement = false;

    writer.writeStartDocument();
    writer.writeStartElement("posts");
    writer.writeCharacters("\n");
    while (reader.hasNext() && questionCount < limit) {
        switch (reader.next()) {
        case XMLEvent.START_ELEMENT:
            if (reader.getLocalName().equals("row")) {
                attrCount = reader.getAttributeCount();
                for (int i = 0; i < attrCount; i++) {
                    // copy only the questions.
                    if (reader.getAttributeName(i).getLocalPart().equals("PostTypeId")
                            && reader.getAttributeValue(i).equals("1")) {
                        copyElement = true;
                        break;
                    }
                }

                if (copyElement) {
                    writer.writeCharacters("  ");
                    writer.writeStartElement("row");
                    for (int i = 0; i < attrCount; i++) {
                        writer.writeAttribute(reader.getAttributeName(i).getLocalPart(),
                                reader.getAttributeValue(i));
                    }
                    writer.writeEndElement();
                    writer.writeCharacters("\n");
                    copyElement = false;
                    questionCount++;
                }
            }
            break;
        }
    }
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();

    return questionCount;
}