App下載
首頁(yè)javadomJava HTML/XML - 如何在DOM中插入xml:space =\'preserve\'

Java HTML/XML - 如何在DOM中插入xml:space =\'preserve\'

我們想知道如何在DOM中插入xml:space =\'preserve\'。
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();

        Element rootElement = document.createElement("root");
        document.appendChild(rootElement);
        rootElement.setAttributeNS(XMLConstants.XML_NS_URI, "space", "preserve");

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(document), new StreamResult(System.out));
    }

}