9

我想将 xml 字符串转换为 xml 文件。我得到一个 xml 字符串作为输出,到目前为止我有以下代码:

public static void stringToDom(String xmlSource) 
    throws SAXException, ParserConfigurationException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
        //return builder.parse(new InputSource(new StringReader(xmlSource)));
    }

但是我不太确定我从这里去哪里。我没有在任何地方创建文件,那么如何将其合并到其中?

我将我的 xml 字符串传递给 xmlSource。

4

4 回答 4

30

如果您只想将 String 的内容放入文件中,那么它是否实际上是 XML 并不重要。您可以跳过解析(这是一个相对昂贵的操作)并直接转储String到文件,如下所示:

public static void stringToDom(String xmlSource) 
        throws IOException {
    java.io.FileWriter fw = new java.io.FileWriter("my-file.xml");
    fw.write(xmlSource);
    fw.close();
}

如 Joachim 所指出的,如果您想安全起见并规避编码问题,则需要进行解析。由于从不信任您的输入是一种很好的做法,因此这可能是更可取的方式。它看起来像这样:

public static void stringToDom(String xmlSource) 
        throws SAXException, ParserConfigurationException, IOException {
    // Parse the given input
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));

    // Write the parsed document to an xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);

    StreamResult result =  new StreamResult(new File("my-file.xml"));
    transformer.transform(source, result);
}
于 2013-07-25T09:07:17.513 回答
2
public static void stringToDom(String xmlSource) throws SAXException, ParserConfigurationException, IOException, TransformerException{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
    // Use a Transformer for output
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();

    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("c:/temp/test.xml"));
    transformer.transform(source, result);
}  

来源:http ://docs.oracle.com/javaee/1.4/tutorial/doc/JAXPXSLT4.html

于 2013-07-25T09:14:09.527 回答
1

If your XML string is clean and ready to be written, why don't you copy it into a file with .xml at the end ?

With Java 1.7 :

Path pathXMLFile = Paths.get("C:/TEMP/TOTO.XML");
Files.write(pathXMLFile, stringXML.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE);

Easy and quick :)

于 2013-07-25T09:10:09.887 回答
-1

只需将 XML 字符串的内容复制到另一个扩展名为 .xml 的文件中。您可以将 java.io 用于相同的 .

于 2013-07-25T09:06:38.670 回答