我想将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。
答案 0 :(得分:25)
如果您只想将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);
}
答案 1 :(得分:1)
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
答案 2 :(得分:0)
只需将XML字符串的内容复制到扩展名为.xml的另一个文件即可。你可以使用java.io。
答案 3 :(得分:0)
如果您的XML字符串是干净的并且可以写入,那么为什么不将它复制到最后带有.xml的文件中?
使用Java 1.7:
Path pathXMLFile = Paths.get("C:/TEMP/TOTO.XML");
Files.write(pathXMLFile, stringXML.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
简单快捷:)