Java 怎么从DOM节点获取XML字符串

2019年7月23日22:46:38Java 怎么从DOM节点获取XML字符串已关闭评论 339 1171字阅读3分54秒

1.简介

Java 怎么从DOM节点获取XML字符串?——请看下文。

2.示例代码

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



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

public class Main {
    public final static String getXml(Node node) {
        
        StringBuilder buffer = new StringBuilder();

        if (node == null) {
            return "";
        }

        if (node instanceof Document) {
            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            buffer.append(getXml(((Document) node).getDocumentElement()));
        } else if (node instanceof Element) {
            Element element = (Element) node;
            buffer.append("<");
            buffer.append(element.getNodeName());
            if (element.hasAttributes()) {
                NamedNodeMap map = element.getAttributes();
                for (int i = 0; i < map.getLength(); i++) {
                    Node attr = map.item(i);
                    buffer.append(" ");
                    buffer.append(attr.getNodeName());
                    buffer.append("=\"");
                    buffer.append(attr.getNodeValue());
                    buffer.append("\"");
                }
            }
            buffer.append(">");
            NodeList children = element.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                buffer.append(getXml(children.item(i)));
            }
            buffer.append("</");
            buffer.append(element.getNodeName());
            buffer.append(">\n");
        } else if (node != null && node.getNodeValue() != null) {
            buffer.append(node.getNodeValue());
        }

        return buffer.toString();
    }
}

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