Java - 如何将 XML 字符串转换为 XML 文件? [英] Java - how to convert a XML string into an XML file?

查看:99
本文介绍了Java - 如何将 XML 字符串转换为 XML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wanting to convert a xml string to a xml file. I am getting a xml string as an out put and I have the following code so far:

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

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

However Im not too sure where I go from here. I am not creating the file anywhere, so how do I incorporate that into it?

我正在将我的 xml 字符串传递到 xmlSource.

I am passing my xml string into xmlSource.

推荐答案

如果你只是想把一个 String 的内容放在一个文件中,它是否真的是 XML 并不重要.您可以跳过解析(这是一个相对昂贵的操作),只需将 String 转储到文件,如下所示:

If you just want to put the content of a String in a file, it doesn't really matter whether it is actually XML or not. You can skip the parsing (which is a relatively expensive operation) and just dump the String to file, like so:

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 所指出的,您将需要解析.由于永远不要相信您的输入是一种很好的做法,因此这可能是更好的方法.它看起来像这样:

If you want to be on the safe side and circumvent encoding issues, as pointed by Joachim, you would need parsing however. Since its good practice to never trust your inputs, this might be the preferable way. It would look like this:

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

这篇关于Java - 如何将 XML 字符串转换为 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆