Example usage for org.w3c.dom NamedNodeMap item

List of usage examples for org.w3c.dom NamedNodeMap item

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap item.

Prototype

public Node item(int index);

Source Link

Document

Returns the indexth item in the map.

Usage

From source file:de.betterform.xml.dom.DOMUtil.java

/**
 * copies all attributes from one Element to another
 *
 * @param from   - the Element which the source attributes
 * @param to     - the target Element for the Attributes
 * @param filter - a NodeFilter to apply during copy
 *///w  ww.j av a 2 s . c o m
public static void copyAttributes(Element from, Element to, NodeFilter filter) {
    if ((from != null) && (to != null)) {
        NamedNodeMap map = from.getAttributes();

        /* if filter is null use our own default filter, which accepts
           everything (this saves us from always check if filter is
           null */
        if (filter == null) {
            filter = new NodeFilter() {
                public short acceptNode(Node n) {
                    return NodeFilter.FILTER_ACCEPT;
                }
            };
        }

        if (map != null) {
            int len = map.getLength();

            for (int i = 0; i < len; i++) {
                Node attr = map.item(i);

                if (attr.getNodeType() == Node.ATTRIBUTE_NODE) {
                    if (filter.acceptNode(attr) == NodeFilter.FILTER_ACCEPT) {
                        to.setAttributeNS(attr.getNamespaceURI(), attr.getNodeName(), attr.getNodeValue());
                    }
                }
            }
        }
    }
}

From source file:com.microsoft.exchange.impl.ExchangeResponseUtilsImpl.java

private String parseInnerResponse(ResponseMessageType responseMessage) {
    StringBuilder responseBuilder = new StringBuilder("Response[");

    ResponseCodeType responseCode = responseMessage.getResponseCode();
    if (null != responseCode) {
        responseBuilder.append("code=" + responseCode + ", ");
    }//from w w  w. j  a  v  a 2s . c o m
    ResponseClassType responseClass = responseMessage.getResponseClass();
    if (null != responseClass) {
        responseBuilder.append("class=" + responseClass + ", ");
    }
    String messageText = responseMessage.getMessageText();
    if (StringUtils.isNotBlank(messageText)) {
        responseBuilder.append("txt=" + messageText + ", ");
    }
    MessageXml messageXml = responseMessage.getMessageXml();
    if (null != messageXml) {
        StringBuilder xmlStringBuilder = new StringBuilder("messageXml=");
        List<Element> anies = messageXml.getAnies();
        if (!CollectionUtils.isEmpty(anies)) {
            for (Element element : anies) {
                String elementNameString = element.getNodeName();
                String elementValueString = element.getNodeValue();
                xmlStringBuilder.append(elementNameString + "=" + elementValueString + ";");

                if (null != element.getAttributes()) {
                    NamedNodeMap attributes = element.getAttributes();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        Node item = attributes.item(i);
                        String nodeName = item.getNodeName();
                        String nodeValue = item.getNodeValue();
                        xmlStringBuilder.append(nodeName + "=" + nodeValue + ",");
                    }
                }
            }
        }
        responseBuilder.append("xml=" + xmlStringBuilder.toString() + ", ");
    }
    Integer descriptiveLinkKey = responseMessage.getDescriptiveLinkKey();
    if (null != descriptiveLinkKey) {
        responseBuilder.append("link=" + descriptiveLinkKey);
    }

    responseBuilder.append("]");
    return responseBuilder.toString();
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.TextWriter.java

private void element(Writer writer, Element elem) throws IOException {
    if (prettyPrint) {
        checkTextBuffer(writer);//w  ww. ja  v  a  2  s.  c om
        indent(writer);
    }

    String n = elem.getTagName();
    writer.write('<');
    writeText(writer, n);

    NamedNodeMap a = elem.getAttributes();
    int size = a.getLength();
    for (int i = 0; i < size; i++) {
        Attr att = (Attr) a.item(i);
        writer.write(' ');
        writeNode(writer, att);
    }

    if (elem.hasChildNodes()) {
        writer.write('>');

        if (prettyPrint) {
            String text = getChildText(elem);
            if (text != null)
                writeEscapedText(writer, normalizeString(text), false);
            else {
                writer.write('\n');
                indentLevel++;
                writeChildren(writer, elem);
                checkTextBuffer(writer);
                indentLevel--;
                indent(writer);
            }
        } else
            writeChildren(writer, elem);

        writer.write("</");
        writeText(writer, n);
        writer.write('>');
    } else {
        if (produceHTML)
            writer.write(">");
        else
            writer.write("/>");
    }

    if (prettyPrint)
        writer.write('\n');
}

From source file:com.marklogic.dom.NodeImpl.java

/** {@inheritDoc} */
public boolean isEqualNode(Node other) {

    // Note that normalization can affect equality; to avoid this,
    // nodes should be normalized before being compared.
    // For the moment, normalization cannot be done.
    if (other == null)
        return false;
    if (getNodeType() != other.getNodeType())
        return false;
    if (!getLocalName().equals(other.getLocalName()))
        return false;
    if (notequals(getNamespaceURI(), other.getNamespaceURI()))
        return false;
    if (notequals(getPrefix(), other.getPrefix()))
        return false;
    if (notequals(getNodeValue(), other.getNodeValue()))
        return false;
    if (hasChildNodes() != other.hasChildNodes())
        return false;
    if (hasAttributes() != other.hasAttributes())
        return false;
    if (hasChildNodes()) {
        NamedNodeMap thisAttr = getAttributes();
        NamedNodeMap otherAttr = other.getAttributes();
        if (thisAttr.getLength() != otherAttr.getLength())
            return false;
        for (int i = 0; i < thisAttr.getLength(); i++)
            if (thisAttr.item(i).isEqualNode(otherAttr.item(i)))
                return false;
    }//from  w w  w  .j a v a 2s  . c o  m
    if (hasAttributes()) {
        NodeList thisChild = getChildNodes();
        NodeList otherChild = other.getChildNodes();
        if (thisChild.getLength() != otherChild.getLength())
            return false;
        for (int i = 0; i < thisChild.getLength(); i++)
            if (thisChild.item(i).isEqualNode(otherChild.item(i)))
                return false;
    }
    return true;
}

From source file:org.adl.samplerte.server.LMSManifestHandler.java

License:asdf

/****************************************************************************
 ** /*ww w  . j  ava  2 s  .  c o m*/
 ** Method: sortAttributes() Input: NamedNodeMap attrs - The list of
 * attributes Output: Attr[] - Sorted array of attributes Description: This
 * method returns an array of sorted attributes.
 ** 
 ** Side Effects: none
 ** 
 ***************************************************************************/
protected Attr[] sortAttributes(NamedNodeMap attrs) {
    int len = (attrs != null) ? attrs.getLength() : 0;
    Attr array[] = new Attr[len];
    for (int i = 0; i < len; i++) {
        array[i] = (Attr) attrs.item(i);
    }
    for (int i = 0; i < len - 1; i++) {
        String name = array[i].getNodeName();
        int index = i;
        for (int j = i + 1; j < len; j++) {
            String curName = array[j].getNodeName();
            if (curName.compareTo(name) < 0) {
                name = curName;
                index = j;
            }
        }
        if (index != i) {
            Attr temp = array[i];
            array[i] = array[index];
            array[index] = temp;
        }
    }

    return (array);

}

From source file:org.pegadi.server.article.ArticleServerImpl.java

/**
 * Change the main tag name of an article. Used when the article type changes.
 *
 * @param art The article.//from   ww w .j  a v  a 2  s  .c  o m
 * @param ID  The ID of the new article type.
 */
protected void changeArticleType(Article art, int ID) {
    Map<String, Object> map = template.queryForMap("SELECT tagname FROM ArticleType WHERE ID=:id",
            Collections.singletonMap("id", ID));
    String tag = (String) map.get("tagname");

    Document doc = art.getDocument();
    if (doc == null) {
        art.parseText();
        doc = art.getDocument();
    }

    if (doc == null) {
        log.error("changeArticleType: Can't get document for article, article is NOT changed.");
        return;
    }

    Element root = doc.getDocumentElement();
    log.info("Root before: " + doc.getDocumentElement().toString());

    Element replace = doc.createElement(tag);

    NamedNodeMap att = root.getAttributes();

    for (int i = 0; i < att.getLength(); i++) {
        Node n = att.item(i);
        if (n instanceof Attr) {
            replace.setAttribute(((Attr) n).getName(), ((Attr) n).getValue());
        }
    }

    NodeList nl = root.getChildNodes();
    log.info("changeArticleType: Root node has {} children.", nl.getLength());
    for (int i = 0; i < nl.getLength(); i++) {
        Node clone = nl.item(i).cloneNode(true);
        log.info("Adding node {} to replace", (i + 1));
        replace.appendChild(clone);
    }

    log.info("Replacement node: {}", replace.toString());

    doc.replaceChild(replace, root);

    log.info("Root after: {}", doc.getDocumentElement().toString());

    if (!art.serialize()) {
        log.error("changeArticleType: Can't serialize the changed XML.");
    }
}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapter.java

private String getAttribute(Node node, String attributeName) {
    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attributeNode = attributes.item(i);
        if (attributeNode.getNodeName().equals(attributeName)) {
            return attributeNode.getNodeValue();
        }/*from w w w . j  a  v a2 s.  c  o  m*/
    }
    return null;
}

From source file:uk.co.markfrimston.tasktree.TaskTree.java

protected boolean nodesEqual(Node a, Node b) {
    if ((a == null) != (b == null)) {
        return false;
    }/*from  ww w.j  a va  2s  .  c  o m*/
    if (a != null) {
        if (a.getNodeType() != b.getNodeType()) {
            return false;
        }
        if ((a.getNodeName() == null) != (b.getNodeName() == null)) {
            return false;
        }
        if (a.getNodeName() != null && !a.getNodeName().equals(b.getNodeName())) {
            return false;
        }
        if ((a.getNodeValue() == null) != (b.getNodeValue() == null)) {
            return false;
        }
        if (a.getNodeValue() != null && !a.getNodeValue().equals(b.getNodeValue())) {
            return false;
        }
        NamedNodeMap attrsA = a.getAttributes();
        Map<String, String> attrMapA = new HashMap<String, String>();
        if (attrsA != null) {
            for (int i = 0; i < attrsA.getLength(); i++) {
                Attr att = (Attr) attrsA.item(i);
                attrMapA.put(att.getName(), att.getValue());
            }
        }
        NamedNodeMap attrsB = b.getAttributes();
        Map<String, String> attrMapB = new HashMap<String, String>();
        if (attrsB != null) {
            for (int i = 0; i < attrsB.getLength(); i++) {
                Attr att = (Attr) attrsB.item(i);
                attrMapB.put(att.getName(), att.getValue());
            }
        }
        if (!attrMapA.equals(attrMapB)) {
            return false;
        }

        Node childA = a.getFirstChild();
        Node childB = b.getFirstChild();
        while (childA != null) {
            if (!nodesEqual(childA, childB)) {
                return false;
            }
            childA = childA.getNextSibling();
            childB = childB.getNextSibling();
        }
        if (childB != null) {
            return false;
        }
    }
    return true;
}

From source file:spec.schema.SchemaCurrent_TO_2008_02_Test.java

/**
 * Checks if the <code>Pixels</code> tag was correctly transformed.
 * /*from   ww w.j  a  v  a  2s .  c o  m*/
 * @param destNode The node from the transformed file.
 * @param srcNode The Image node from the source file
 */
private void checkPixelsNode(Node destNode, Node srcNode) {
    // store the values for ID and Name attribute on the input node
    NamedNodeMap attributesSrc = srcNode.getAttributes();
    String nameSrc = "";
    String idSrc = "";
    String sizeX = "";
    String sizeY = "";
    String sizeZ = "";
    String sizeC = "";
    String sizeT = "";
    String pixelsType = "";
    String dimensionOrder = "";
    Node n;
    String name;
    for (int i = 0; i < attributesSrc.getLength(); i++) {
        n = attributesSrc.item(i);
        name = n.getNodeName();
        if (name.equals(XMLWriter.ID_ATTRIBUTE))
            idSrc = n.getNodeValue();
        else if (name.equals(XMLWriter.NAME_ATTRIBUTE))
            nameSrc = n.getNodeValue();
        else if (name.equals(XMLWriter.SIZE_X_ATTRIBUTE))
            sizeX = n.getNodeValue();
        else if (name.equals(XMLWriter.SIZE_Y_ATTRIBUTE))
            sizeY = n.getNodeValue();
        else if (name.equals(XMLWriter.SIZE_Z_ATTRIBUTE))
            sizeZ = n.getNodeValue();
        else if (name.equals(XMLWriter.SIZE_C_ATTRIBUTE))
            sizeC = n.getNodeValue();
        else if (name.equals(XMLWriter.SIZE_T_ATTRIBUTE))
            sizeT = n.getNodeValue();
        else if (name.equals(XMLWriter.PIXELS_TYPE_ATTRIBUTE))
            pixelsType = n.getNodeValue();
        else if (name.equals(XMLWriter.DIMENSION_ORDER_ATTRIBUTE))
            dimensionOrder = n.getNodeValue();
    }
    String bigEndianDst = "";
    NamedNodeMap attributes = destNode.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        n = attributes.item(i);
        if (n != null) {
            name = n.getNodeName();
            if (name.equals(XMLWriter.ID_ATTRIBUTE))
                assertEquals(n.getNodeValue(), idSrc);
            else if (name.equals(XMLWriter.NAME_ATTRIBUTE))
                assertEquals(n.getNodeValue(), nameSrc);
            else if (name.equals(XMLWriter.SIZE_X_ATTRIBUTE))
                assertEquals(n.getNodeValue(), sizeX);
            else if (name.equals(XMLWriter.SIZE_Y_ATTRIBUTE))
                assertEquals(n.getNodeValue(), sizeY);
            else if (name.equals(XMLWriter.SIZE_Z_ATTRIBUTE))
                assertEquals(n.getNodeValue(), sizeZ);
            else if (name.equals(XMLWriter.SIZE_C_ATTRIBUTE))
                assertEquals(n.getNodeValue(), sizeC);
            else if (name.equals(XMLWriter.SIZE_T_ATTRIBUTE))
                assertEquals(n.getNodeValue(), sizeT);
            //            else if (name.equals(XMLWriter.PIXELS_TYPE_ATTRIBUTE))
            //               assertEquals(n.getNodeValue(), pixelsType);
            else if (name.equals(XMLWriter.DIMENSION_ORDER_ATTRIBUTE))
                assertEquals(n.getNodeValue(), dimensionOrder);
            else if (name.equals(XMLWriter.BIG_ENDIAN_ATTRIBUTE))
                //  - also store the Big Endian value used in the output
                bigEndianDst = n.getNodeValue();
        }
    }
    // Create two arrays of BinData nodes
    NodeList list = srcNode.getChildNodes();
    List<Node> binDataNodeSrc = new ArrayList<Node>();
    for (int i = 0; i < list.getLength(); i++) {
        n = list.item(i);
        if (n != null) {
            name = n.getNodeName();
            if (name.contains(XMLWriter.BIN_DATA_TAG))
                //  - Add node to the input list
                binDataNodeSrc.add(n);
        }
    }
    list = destNode.getChildNodes();
    List<Node> binDataNodeDest = new ArrayList<Node>();
    for (int i = 0; i < list.getLength(); i++) {
        n = list.item(i);
        if (n != null) {
            name = n.getNodeName();
            if (name.contains(XMLWriter.BIN_DATA_TAG))
                //  - Add node to the output list
                binDataNodeDest.add(n);
        }
    }
    // Compare the lengths of the lists
    assertTrue(binDataNodeSrc.size() > 0);
    assertEquals(binDataNodeSrc.size(), binDataNodeDest.size());
    // Compare the contents of the lists
    for (int i = 0; i < binDataNodeDest.size(); i++) {
        checkBinDataNode(binDataNodeDest.get(i), binDataNodeSrc.get(i));
    }
    // Compare the Big Endian value from the output stored above 
    // with the value used in the input file
    n = binDataNodeSrc.get(0);
    attributesSrc = n.getAttributes();
    //now check that 
    for (int i = 0; i < attributesSrc.getLength(); i++) {
        n = attributesSrc.item(i);
        if (n != null) {
            name = n.getNodeName();
            if (name.contains(XMLWriter.BIG_ENDIAN_ATTRIBUTE))
                assertEquals(n.getNodeValue(), bigEndianDst);
        }
    }
}

From source file:org.mitre.stix.STIXSchema.java

/**
 * Private constructor to permit a single STIXSchema to exists.
 *///from ww w  .jav  a  2  s .c  o  m
private STIXSchema() {

    this.version = ((Version) this.getClass().getPackage().getAnnotation(Version.class)).schema();

    ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(
            this.getClass().getClassLoader());
    Resource[] schemaResources;

    try {
        schemaResources = patternResolver.getResources("classpath:schemas/v" + version + "/**/*.xsd");

        prefixSchemaBindings = new HashMap<String, String>();

        String url, prefix, targetNamespace;
        Document schemaDocument;
        NamedNodeMap attributes;
        Node attribute;

        for (Resource resource : schemaResources) {

            url = resource.getURL().toString();

            schemaDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(resource.getInputStream());

            schemaDocument.getDocumentElement().normalize();

            attributes = schemaDocument.getDocumentElement().getAttributes();

            for (int i = 0; i < attributes.getLength(); i++) {

                attribute = attributes.item(i);

                targetNamespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace");

                if (attribute.getNodeName().startsWith("xmlns:")
                        && attribute.getNodeValue().equals(targetNamespace)) {

                    prefix = attributes.item(i).getNodeName().split(":")[1];

                    if ((prefixSchemaBindings.containsKey(prefix))
                            && (prefixSchemaBindings.get(prefix).split("schemas/v" + version + "/")[1]
                                    .startsWith("external"))) {

                        continue;

                    }

                    LOGGER.fine("     adding: " + prefix + " :: " + url);

                    prefixSchemaBindings.put(prefix, url);
                }
            }
        }

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Source[] schemas = new Source[prefixSchemaBindings.values().size()];

        int i = 0;
        for (String schemaLocation : prefixSchemaBindings.values()) {
            schemas[i++] = new StreamSource(schemaLocation);
        }

        schema = factory.newSchema(schemas);

        validator = schema.newValidator();
        validator.setErrorHandler(new ValidationErrorHandler());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}