Example usage for org.w3c.dom NamedNodeMap getLength

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

Introduction

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

Prototype

public int getLength();

Source Link

Document

The number of nodes in this map.

Usage

From source file:Main.java

protected static void writeXMLwalkTree(Node node, int indent, PrintWriter out) {
    if (node == null)
        throw new NullPointerException("Null node passed to writeXMLwalkTree()");
    if (node.hasChildNodes()) {
        if (node instanceof Element) {
            Element elem = (Element) node;
            //elem.normalize();
            out.print("\n");
            for (int j = 0; j < indent; j++) {
                out.print(" ");
            }/*from   ww w.j  a va  2  s. c o  m*/
            out.print("<" + elem.getTagName());
            NamedNodeMap attrs = elem.getAttributes();
            for (int i = 0; i < attrs.getLength(); i++) {
                Attr a = (Attr) attrs.item(i);
                out.print(" " + a.getName() + "=\"" + a.getValue() + "\"");
            }
            out.print(">");
            NodeList nl = node.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                writeXMLwalkTree(nl.item(i), indent + 2, out);
            }
            //              for(int j=0;j<indent;j++) {
            //                  out.print(" ");
            //              }
            out.println("</" + elem.getTagName() + ">");
        }
    } else {
        if (node instanceof Element) {
            Element elem = (Element) node;
            out.print("\n");
            for (int j = 0; j < indent; j++) {
                out.print(" ");
            }
            out.print("<" + elem.getTagName());
            NamedNodeMap attrs = elem.getAttributes();
            for (int i = 0; i < attrs.getLength(); i++) {
                Attr a = (Attr) attrs.item(i);
                out.print(" " + a.getName() + "=\"" + a.getValue() + "\"");
            }
            out.println("/>");
        } else if (node instanceof CDATASection) {
            CDATASection cdata = (CDATASection) node;
            //              for(int j=0;j<indent;j++) {
            //                  out.print(" ");
            //              }
            out.print("<![CDATA[" + cdata.getData() + "]]>");
        } else if (node instanceof Text) {
            Text text = (Text) node;
            StringBuilder buf = new StringBuilder(text.getData().length());
            for (int i = 0; i < text.getData().length(); i++) {
                if (text.getData().charAt(i) == '\n' || text.getData().charAt(i) == '\r'
                        || text.getData().charAt(i) == ' ' || text.getData().charAt(i) == '\t') {
                    if (buf.length() > 0 && buf.charAt(buf.length() - 1) != ' ') {
                        buf.append(' ');
                    }
                } else {
                    buf.append(text.getData().charAt(i));
                }
            }
            if (buf.length() > 0 && !buf.toString().equals(" ")) {
                StringBuilder buf2 = new StringBuilder(buf.length() + indent);
                //                  for(int j=0;j<indent;j++) {
                //                      buf2.append(' ');
                //                  }
                buf2.append(buf.toString());
                out.print(buf2);
            }
        }
    }
}

From source file:Main.java

public static String getNamespaceURI(Element el, String prefix) {
    if ((prefix == null) || (prefix.length() < 1)) {
        return "";
    }/*from   w  w  w .ja v a 2  s .  c o  m*/
    prefix = prefix.trim();
    try {
        NamedNodeMap map = el.getOwnerDocument().getDocumentElement().getAttributes();
        for (int j = 0; j < map.getLength(); j++) {
            Node n = map.item(j);
            String attrName = ((Attr) n).getName();
            if (attrName != null) {
                if (attrName.trim().equals("xmlns:" + prefix)) {
                    return ((Attr) n).getValue();
                }
            }
        }
    } catch (Exception e) {
    }

    return "";
}

From source file:Main.java

public static String format(Node n, int indentLevel) {
    String indent = "";
    for (int i = 0; i < indentLevel; i++) {
        indent += "\t";
    }//from w  w w  .  ja v a2  s .  c  o  m

    StringBuilder result = new StringBuilder();
    result.append(indent);
    if (n.getNodeType() == Node.ELEMENT_NODE) {
        result.append("<");
        result.append(n.getNodeName());
        NamedNodeMap attrs = n.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            result.append(" ");
            result.append(attr.getNodeName());
            result.append("=\"");
            result.append(attr.getNodeValue());
            result.append("\"");
        }
        result.append(">\n");
    }

    if (n.getNodeType() == Node.TEXT_NODE) {
        String str = n.getNodeValue();
        result.append(str + "\n");
    }

    NodeList childNodes = n.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node n2 = childNodes.item(i);
        if (isEmptyTextNode(n2)) {
            continue;
        }
        result.append(format(n2, indentLevel + 1));
    }

    if (n.getNodeType() == Node.ELEMENT_NODE) {
        result.append(indent);
        result.append("</");
        result.append(n.getNodeName());
        result.append(">\n");
    }
    return result.toString();
}

From source file:Main.java

private static String logXMLSubNode(Node node, int deepth) {

    int i;//from   w w w . j av  a 2  s .  c  om
    String nodeStr = new String();
    String interStr = new String();
    for (i = 0; i < deepth; i++)
        interStr += "\t";

    nodeStr += interStr + "<" + node.getNodeName() + internal;
    if (node.hasAttributes()) {
        NamedNodeMap attrs = node.getAttributes();

        // add the attrubite name-value pairs
        for (i = 0; i < attrs.getLength(); i++) {
            Node a = attrs.item(i);
            nodeStr += a.getNodeName() + "=" + a.getNodeValue() + internal;
        }
    }
    if (node.hasChildNodes()) {
        nodeStr += ">\n";
        NodeList ns = node.getChildNodes();
        for (i = 0; i < ns.getLength(); i++) {
            nodeStr += logXMLSubNode(ns.item(i), deepth + 1);
        }
        nodeStr += interStr + "</" + node.getNodeName() + ">\n";
    } else {
        if (node.getNodeValue() != null) {
            nodeStr += ">" + node.getNodeValue() + "<" + node.getNodeName();
        }
        nodeStr += "/>\n";
    }
    return nodeStr;
}

From source file:Main.java

private static void serializeElement(StringBuilder sb, Element element, int tabIndex) {
    sb.append('\n');
    for (int i = 0; i < tabIndex; i++) {
        sb.append('\t');
    }//ww  w  .  j a v  a2  s. c om
    sb.append("<");
    sb.append(element.getTagName());
    if (element.hasAttributes()) {
        NamedNodeMap attributes = element.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);

            sb.append(" ");
            sb.append(attribute.getNodeName());
            sb.append("=");
            sb.append("\"");
            String value = attribute.getNodeValue();
            sb.append(value.replace("\"", "\\\""));
            sb.append("\"");
        }
    }
    sb.append(">");
    NodeList nodeList = element.getChildNodes();
    ArrayList<Element> childElements = new ArrayList<Element>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);
        if (childNode instanceof Element) {
            childElements.add((Element) childNode);
        }
    }
    if (childElements.size() == 0) {
        sb.append(escapeInvalidCharacters(getTextContent(element)));
    } else {
        for (Element childElement : childElements) {
            serializeElement(sb, childElement, tabIndex + 1);
        }
        sb.append('\n');
        for (int i = 0; i < tabIndex; i++) {
            sb.append('\t');
        }
    }
    sb.append("</");
    sb.append(element.getTagName());
    sb.append(">");
}

From source file:Utils.java

public static String elementToString(Node n) {

    String name = n.getNodeName();

    short type = n.getNodeType();

    if (Node.CDATA_SECTION_NODE == type) {
        return "<![CDATA[" + n.getNodeValue() + "]]&gt;";
    }/*from  www  .  j a va2  s .  c  o  m*/

    if (name.startsWith("#")) {
        return "";
    }

    StringBuffer sb = new StringBuffer();
    sb.append('<').append(name);

    NamedNodeMap attrs = n.getAttributes();
    if (attrs != null) {
        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            sb.append(' ').append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append("\"");
        }
    }

    String textContent = null;
    NodeList children = n.getChildNodes();

    if (children.getLength() == 0) {
        if ((textContent = XMLUtil.getTextContent(n)) != null && !"".equals(textContent)) {
            sb.append(textContent).append("</").append(name).append('>');
            ;
        } else {
            sb.append("/>").append('\n');
        }
    } else {
        sb.append('>').append('\n');
        boolean hasValidChildren = false;
        for (int i = 0; i < children.getLength(); i++) {
            String childToString = elementToString(children.item(i));
            if (!"".equals(childToString)) {
                sb.append(childToString);
                hasValidChildren = true;
            }
        }

        if (!hasValidChildren && ((textContent = XMLUtil.getTextContent(n)) != null)) {
            sb.append(textContent);
        }

        sb.append("</").append(name).append('>');
    }

    return sb.toString();
}

From source file:Main.java

/** Transform xml element and children into a string
 *
 * @param nd Node root of elements to transform
 * @return String representation of xml/*from  w  w  w  .  j  a v  a  2 s.co  m*/
 */
public static String elementToString(Node nd, boolean add_newlines) {
    //short type = n.getNodeType();

    if (Node.CDATA_SECTION_NODE == nd.getNodeType()) {
        return "<![CDATA[" + nd.getNodeValue() + "]]&gt;";
    }

    // return if simple element type
    final String name = nd.getNodeName();
    if (name.startsWith("#")) {
        if (name.equals("#text"))
            return nd.getNodeValue();
        return "";
    }

    // output name
    String ret = "<" + name;

    // output attributes
    NamedNodeMap attrs = nd.getAttributes();
    if (attrs != null) {
        for (int idx = 0; idx < attrs.getLength(); idx++) {
            Node attr = attrs.item(idx);
            ret += " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"";
        }
    }

    final String text = nd.getTextContent();
    final NodeList child_ndls = nd.getChildNodes();
    String all_child_str = "";

    for (int idx = 0; idx < child_ndls.getLength(); idx++) {
        final String child_str = elementToString(child_ndls.item(idx), add_newlines);
        if ((child_str != null) && (child_str.length() > 0)) {
            all_child_str += child_str;
        }
    }
    if (all_child_str.length() > 0) {
        // output children
        ret += ">" + (add_newlines ? "\n" : " ");
        ret += all_child_str;
        ret += "</" + name + ">";
    } else if ((text != null) && (text.length() > 0)) {
        // output text
        ret += text;
        ret += "</" + name + ">";
    } else {
        // output nothing
        ret += "/>" + (add_newlines ? "\n" : " ");
    }

    return ret;
}

From source file:Main.java

private static String prettyPrintDom(Node node, String indent, boolean isRoot, boolean escapeStrings) {
    String ret = "";
    switch (node.getNodeType()) {

    case Node.DOCUMENT_NODE:
        // recurse on each child
        NodeList nodes = node.getChildNodes();
        if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {
                ret += prettyPrintDom(nodes.item(i), indent, isRoot, escapeStrings);
            }/*  w ww .  ja  va2 s.  c  o m*/
        }
        break;

    case Node.ELEMENT_NODE:
        String name = node.getNodeName();
        ret += indent + "<" + name;
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node current = attributes.item(i);
            ret += " " + current.getNodeName() + "=\""
                    + ((escapeStrings) ? escapeStringForXML(current.getNodeValue()) : current.getNodeValue())
                    + "\"";
        }
        ret += ">";

        // recurse on each child
        NodeList children = node.getChildNodes();
        if (children != null) {
            for (int i = 0; i < children.getLength(); i++) {
                String tmp = prettyPrintDom(children.item(i), indent + ((isRoot) ? "" : BI), false,
                        escapeStrings);
                if (!tmp.replaceAll("[\\s]+", "").equals(""))
                    if (tmp.endsWith("\n"))
                        if (ret.endsWith("\n"))
                            ret += tmp;
                        else
                            ret += "\n" + tmp;
                    else
                        ret += tmp;
            }
        }
        if (ret.endsWith("\n"))
            ret += indent + "</" + name + ">\n";
        else
            ret += "</" + name + ">\n";
        break;

    case Node.TEXT_NODE:
        ret += (escapeStrings) ? escapeStringForXML(node.getNodeValue()) : node.getNodeValue();
        break;

    case Node.COMMENT_NODE:
        ret += "<!-- " + node.getNodeValue() + " -->";
        break;
    }
    return ret;
}

From source file:Main.java

public static String elementToString(Node n) {

    String name = n.getNodeName();

    short type = n.getNodeType();

    if (Node.CDATA_SECTION_NODE == type) {
        return "<![CDATA[" + n.getNodeValue() + "]]&gt;";
    }//ww  w . j  av a 2 s .  c  o m

    if (name.startsWith("#")) {
        return "";
    }

    StringBuilder sb = new StringBuilder();
    sb.append('<').append(name);

    NamedNodeMap attrs = n.getAttributes();
    if (attrs != null) {
        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            sb.append(' ').append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append("\"");
        }
    }

    String textContent = null;
    NodeList children = n.getChildNodes();

    if (children.getLength() == 0) {
        //      if ((textContent = XMLUtil.getTextContent(n)) != null && !"".equals(textContent)) {
        if ((textContent = n.getTextContent()) != null && !"".equals(textContent)) {
            sb.append(textContent).append("</").append(name).append('>');

        } else {
            sb.append("/>");
        }
    } else {
        sb.append('>');
        boolean hasValidChildren = false;
        for (int i = 0; i < children.getLength(); i++) {
            String childToString = elementToString(children.item(i));
            if (!"".equals(childToString)) {
                sb.append('\n').append(childToString);
                hasValidChildren = true;
            }
        }
        if (hasValidChildren) {
            sb.append('\n');
        }

        //      if (!hasValidChildren && ((textContent = XMLUtil.getTextContent(n)) != null)) {
        if (!hasValidChildren && ((textContent = n.getTextContent()) != null)) {
            sb.append(textContent);
        }

        sb.append("</").append(name).append('>');
    }

    return sb.toString();
}

From source file:Main.java

@Nullable
public static Map<String, String> getAllAttributesAsMap(@Nullable final Element aSrcNode) {
    if (aSrcNode != null) {
        final NamedNodeMap aNNM = aSrcNode.getAttributes();
        if (aNNM != null) {
            final Map<String, String> aMap = new LinkedHashMap<String, String>(aNNM.getLength());
            final int nMax = aNNM.getLength();
            for (int i = 0; i < nMax; ++i) {
                final Attr aAttr = (Attr) aNNM.item(i);
                aMap.put(aAttr.getName(), aAttr.getValue());
            }//from  w w  w .  j  a  v a2 s  .  com
            return aMap;
        }
    }
    return null;
}