A method to get string which represent the xml element - Java XML

Java examples for XML:XML Element Value

Description

A method to get string which represent the xml element

Demo Code


import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import java.io.UnsupportedEncodingException;

public class Main{
    /**//  w ww  . ja v a2  s  . c om
     * A method to get string which represent the xml element
     * @param Element el, a xml element object to get string
     * @param String s, indent string like "   "
     * @return String , a string represent xml
     */
    static public String NodeContext(Element el, String s) {
        Node n = (Node) el;
        boolean enableEsc = true;

        String ret = "";
        ret += "\r\n" + s + "<" + n.getNodeName();
        if (n.hasAttributes()) {
            NamedNodeMap al = n.getAttributes();
            Node an = null;
            for (int i = 0; i < al.getLength(); ++i) {
                an = al.item(i);
                ret += " " + an.getNodeName();
                ret += "=\"" + an.getNodeValue() + "\"";
            }
        }
        NodeList nl = n.getChildNodes();
        if (nl.getLength() > 0)
            ret += ">";
        else
            ret += "/>";

        for (int i = 0; i < nl.getLength(); ++i) {
            n = nl.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                //ret+=(s+n.getNodeName());
                ret += NodeContext((Element) n, s + "   ");
            } else {
                if (n.getNodeType() == Node.TEXT_NODE) {
                    if (enableEsc) {
                        ret += XmlUtil.xmlEsc(n.getNodeValue().trim());
                    } else {
                        ret += n.getNodeValue().trim();
                    }
                }
                if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
                    if (n.getNodeName().substring(0, 9).equals("javax.xml")) {
                        if (n.getNodeName()
                                .equals("javax.xml.transform.disable-output-escaping"))
                            enableEsc = false;
                        if (n.getNodeName()
                                .equals("javax.xml.transform.enable-output-escaping"))
                            enableEsc = true;

                    } else {
                        ret += "<" + n.getNodeName() + " "
                                + n.getNodeValue() + ">";
                    }

                }//else{ret+=n.getNodeType();}

            }
        }
        if (nl.getLength() == 1
                && nl.item(0).getNodeType() == Node.TEXT_NODE)
            ret += "</" + el.getNodeName() + ">";
        else if (nl.getLength() > 0)
            ret += "\r\n" + s + "</" + el.getNodeName() + ">";
        return (ret);
    }
    /**
     * A method to get the value of desire node from xml document
     * @param Node parent, xml's node object to get
     * @return String , value from provided node
     */
    static public String getNodeValue(Node parent) {
        String ret = "";

        Node n = parent.getFirstChild();
        while (n != null) {
            if (n.getNodeType() == Node.TEXT_NODE) {
                try {
                    ret = n.getNodeValue().trim();
                } catch (NullPointerException ex) {
                    ret = "";
                    break;
                }
            }
            n = n.getNextSibling();
        }
        return (ret);
    }
    /**
     * escapes & < > " ' characters to &amp; &lt; $gt; &quot; &apos;
     * @param String, a string to convert
     * @return String, a converted string
     */
    public static String xmlEsc(String str) {

        // test if str contains chars that has to be escaped
        // most strings do not need escape at all, and
        // for such strings this check eliminates
        // creating new string object
        int len = str.length();
        String esc = "'<>\"&";
        boolean needEscape = false;
        for (int i = 0; i < len; i++) {
            if (esc.indexOf(str.charAt(i)) != -1) {
                needEscape = true;
                break;
            }
        }
        if (!needEscape)
            return str;
        else // escape it
        {
            StringBuffer ret = new StringBuffer();
            for (int i = 0; i < len; i++) {
                char c = str.charAt(i);
                switch (c) {
                case '&':
                    ret.append("&amp;");
                    break;
                case '>':
                    ret.append("&gt;");
                    break;
                case '<':
                    ret.append("&lt;");
                    break;
                case '"':
                    ret.append("&quot;");
                    break;
                case '\'':
                    ret.append("&apos;");
                    break;
                default:
                    ret.append(c);
                    break;
                }
            }
            return ret.toString();
        }
    }
}

Related Tutorials