Java - 如何将XML字符串转换为XML文件?

10

我想将一个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个回答

31

如果您只想将字符串的内容放入文件中,那么它实际上是否为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);
}

1
这使用平台默认编码,可能会导致XML文件格式不正确。像OP开始的那样费力一些,但对此更安全。 - Joachim Sauer
如何使用此方法在 XML 文件中设置标签之间的字符串或值?例如,在 XML 文件中,我有 <ExceptionCode></ExceptionCode> 和 <ExceptionMessage></ExceptionMessage>。 - user6248190
builder.parse(new InputSource(new StringReader(xmlSource)));是无效的。(DocumentBuilder中的parse(InputStream)方法不适用于参数(InputSource)) - Steve Staple

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

这篇文章介绍了Java API for XML Processing(JAXP)中的XSL转换器。XSL是一种XML风格表单语言,用于将XML文档转换为其他格式,例如HTML或PDF。JAXP提供了一个标准接口,使得开发人员可以使用不同的XSLT引擎来执行转换。本教程还包括如何编写Java代码来配置和使用XSL转换器的示例。

1
如果您的XML字符串已经干净并准备好被写入,为什么不将其复制到以.xml结尾的文件中呢?
使用Java 1.7:
Path pathXMLFile = Paths.get("C:/TEMP/TOTO.XML");
Files.write(pathXMLFile, stringXML.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE);

简单快捷 :)

1
stringXML.getBytes() 获取平台默认编码的字节。在此处应使用与 XML 标头中使用的相同编码,以避免稍后解析该文件时出现问题。 - jlordo
这种情况很少见。 - jlordo

-1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接