将新的XML节点保存到文件

将新的XML节点保存到文件

本文介绍了将新的XML节点保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将包含 XML nodeList 节点保存为新文件,这里是Node列表获得一个新的 XML doc并拆分成较小的 XML

I am trying to save nodeList node that contains XML as a new file, here is the Node list that get a new XML doc and split to smaller XMLs:

public void split(Document inDocument) throws ParserConfigurationException,
            SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        SaveXML savePerJob = new SaveXML();
        // Load the input XML document, parse it and return an instance of the
        // Document class.
        Document document = inDocument;
        //all elements
        //jobs
        NodeList nodes = document.getDocumentElement().getChildNodes();
        NodeList jobs = nodes.item(7).getChildNodes();
        for(int j =0; j<jobs.getLength(); j++){
            Node itm = jobs.item(j);
            String itmName = itm.getFirstChild().getNodeName();
            String itmID = itm.getFirstChild().getTextContent();
            System.out.println("name: " + itmName + " value: " + itmID);
            //here I want to save the node as a new .xml file
        }
    }

输出是一个很长的列表,如:

the output is a long list like :

name: id value: 9496425

现在我想将节点 itm 保存为新的 .xml 文件,我没有找到返回节点的功能。
谢谢。

Now I want to save the node itm as new new .xml file and I didnt find the function that returns the node as is.Thanks.

推荐答案

您可以将您的节点转换为字符串,并将此字符串保存为 .xml 文件。

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

下面的方法将一个节点变成xml字符串。这是一个JDK唯一的解决方案,不需要依赖。

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);
    }
}

这篇关于将新的XML节点保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:32