Java 怎么将元素转为字符串

2019年8月11日20:49:36Java 怎么将元素转为字符串已关闭评论 392 1423字阅读4分44秒

1.简介

Java 怎么将元素转为字符串?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static String elementsToString(NodeList nls, boolean add_newlines) {

        String ret = "";
        for (int i = 0; i < nls.getLength(); i++) {
            final String nextstr = elementToString(nls.item(i),
                    add_newlines).trim();
            if (nextstr.length() > 0) {
                if (ret.length() > 0)
                    ret += (add_newlines) ? "\n" : " ";
                ret += nextstr;
            }
        }
        return ret;
    }

    
    public static String elementToString(Node nd, boolean add_newlines) {
        

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

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

        
        String ret = "<" + name;

        
        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) {
            
            ret += ">" + (add_newlines ? "\n" : " ");
            ret += all_child_str;
            ret += "</" + name + ">";
        } else if ((text != null) && (text.length() > 0)) {
            
            ret += text;
            ret += "</" + name + ">";
        } else {
            
            ret += "/>" + (add_newlines ? "\n" : " ");
        }

        return ret;
    }
}

 
继续阅读
编程十万个怎么办