Java 怎么将XML文档(Document)转为字符串

2019年7月29日19:29:07Java 怎么将XML文档(Document)转为字符串已关闭评论 383 2816字阅读9分23秒

1.简介

Java 怎么将XML文档(Document)转为字符串?——请看下文。

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;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Main {
    public static String documentToString(Document document)
            throws Exception {
        return documentToString(document, true);
    }

    public static String documentToString(Document document,
            boolean standalone) throws Exception {
        String prol = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\""
                + (standalone ? "yes" : "no") + "\"?>";
        return prol
                + nodeToString(document.getDocumentElement(),
                        new HashSet(), document.getDocumentElement()
                                .getNamespaceURI());
    }

    protected static String nodeToString(Node node,
            Set<String> parentPrefixes, String namespaceURI)
            throws Exception {
        StringBuilder b = new StringBuilder();

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

        if (node instanceof Element) {
            Element element = (Element) node;
            b.append("<");
            b.append(element.getNodeName());

            Map<String, String> thisLevelPrefixes = new HashMap();
            if (element.getPrefix() != null
                    && !parentPrefixes.contains(element.getPrefix())) {
                thisLevelPrefixes.put(element.getPrefix(),
                        element.getNamespaceURI());
            }

            if (element.hasAttributes()) {
                NamedNodeMap map = element.getAttributes();
                for (int i = 0; i < map.getLength(); i++) {
                    Node attr = map.item(i);
                    if (attr.getNodeName().startsWith("xmlns"))
                        continue;
                    if (attr.getPrefix() != null
                            && !parentPrefixes.contains(attr.getPrefix())) {
                        thisLevelPrefixes.put(attr.getPrefix(),
                                element.getNamespaceURI());
                    }
                    b.append(" ");
                    b.append(attr.getNodeName());
                    b.append("=\"");
                    b.append(attr.getNodeValue());
                    b.append("\"");
                }
            }

            if (namespaceURI != null
                    && !thisLevelPrefixes.containsValue(namespaceURI)
                    && !namespaceURI.equals(element.getParentNode()
                            .getNamespaceURI())) {
                b.append(" xmlns=\"").append(namespaceURI).append("\"");
            }

            for (Map.Entry<String, String> entry : thisLevelPrefixes
                    .entrySet()) {
                b.append(" xmlns:").append(entry.getKey()).append("=\"")
                        .append(entry.getValue()).append("\"");
                parentPrefixes.add(entry.getKey());
            }

            NodeList children = element.getChildNodes();
            boolean hasOnlyAttributes = true;
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                if (child.getNodeType() != Node.ATTRIBUTE_NODE) {
                    hasOnlyAttributes = false;
                    break;
                }
            }
            if (!hasOnlyAttributes) {
                b.append(">");
                for (int i = 0; i < children.getLength(); i++) {
                    b.append(nodeToString(children.item(i), parentPrefixes,
                            children.item(i).getNamespaceURI()));
                }
                b.append("</");
                b.append(element.getNodeName());
                b.append(">");
            } else {
                b.append("/>");
            }

            for (String thisLevelPrefix : thisLevelPrefixes.keySet()) {
                parentPrefixes.remove(thisLevelPrefix);
            }

        } else if (node.getNodeValue() != null) {
            b.append(encodeText(node.getNodeValue()));
        }

        return b.toString();
    }

    protected static String encodeText(String s) {
        s = s.replaceAll("&", "&");
        s = s.replaceAll("<", "<");
        s = s.replaceAll(">", ">");
        s = s.replaceAll("'", "'");
        s = s.replaceAll("\"", """);
        return s;
    }
}

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