Save new XML node to file

…衆ロ難τιáo~ 提交于 2019-11-29 08:47:23

You can convert your node to a string and save this string into a .xml file.

Convert a node to string

The method below will turn a node into an xml string. It's a JDK only solution, no dependencies required.

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

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.StringWriter;

public static String toString(Node node, boolean omitXmlDeclaration, boolean prettyPrint) {
    if (node == null) {
        throw new IllegalArgumentException("node is null.");
    }

    try {
        // Remove unwanted whitespaces
        node.normalize();
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile("//text()[normalize-space()='']");
        NodeList nodeList = (NodeList)expr.evaluate(node, XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node nd = nodeList.item(i);
            nd.getParentNode().removeChild(nd);
        }

        // Create and setup transformer
        Transformer transformer =  TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        if (omitXmlDeclaration == true) {
           transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }

        if (prettyPrint == true) {
           transformer.setOutputProperty(OutputKeys.INDENT, "yes");
           transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        }

        // Turn the node into a string
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(node), new StreamResult(writer));
        return writer.toString();
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}

Here is one possibility:

void save(Node node, OutputStream stream) throws Exception {
    DOMImplementationLS ls = (DOMImplementationLS) node.getOwnerDocument().getImplementation();
    LSOutput out = ls.createLSOutput();
    out.setByteStream(stream);
    LSSerializer ser = ls.createLSSerializer();
    ser.write(node, out);
}

Perhaps you should make sure that node is really an Element, but I leave that as an excersize.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!