【问题标题】:How to export an XML document to file system如何将 XML 文档导出到文件系统
【发布时间】:2018-11-13 00:38:35
【问题描述】:

我试图将文本文件转换为 xml 文件,但在解析时遇到了一个小问题。

这是将txt文件转换为xml的代码。

public class ToXML {

    BufferedReader in;
    StreamResult out;
    TransformerHandler th;
    AttributesImpl atts;

    public static void main(String args[]) {
        new ToXML().doit();
    }

    public void doit() {
        try {
            in = new BufferedReader(new FileReader("E:/Java Codes/JMartin.txt"));
            out = new StreamResult("E:/Java Codes/JMartin2.xml");
            initXML();
            String str;
            while ((str = in.readLine()) != null) {
                process(str);
            }
            in.close();
            closeXML();
        } catch (IOException | ParserConfigurationException | TransformerConfigurationException | SAXException e) {
        }
    }

    public void initXML() throws ParserConfigurationException,
            TransformerConfigurationException, SAXException {
        SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
                .newInstance();

        th = tf.newTransformerHandler();
        Transformer serializer = th.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
        serializer.setOutputProperty(
                "{http://xml.apache.org/xslt}indent-amount", "4");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        th.setResult(out);
        th.startDocument();
        atts = new AttributesImpl();
        th.startElement("", "", "Author", atts);
    }

    public void process(String s) throws SAXException {
        String[] elements = s.split("<>;");
        atts.clear();
        th.startElement("", "", "Data", atts);
        th.startElement("", "", "AuthorName", atts);
        th.characters(elements[0].toCharArray(), 0, elements[0].length());
        th.endElement("", "", "AuthorName");
        th.endElement("", "", "Data");
    }

    public void closeXML() throws SAXException {
        th.endElement("", "", "Author");
        th.endDocument();
    }
}

在编译过程中,代码运行良好,但如何将 .xml 文件保存在驱动器中?

有什么想法吗?请帮忙。

【问题讨论】:

  • 与您的问题并不真正相关,但有空的 catch 块是不好的做法。至少放一些代码来记录堆栈跟踪以帮助您进行调试。
  • 如我所说,调试没有问题。我只需要帮助来存储 . XML 文件

标签: java xml parsing


【解决方案1】:

您可以使用FileWriter 将 XML 文档导出到 XML 文件中。

public void saveTo(Document document, File file) {
  try (Writer writer = new FileWriter(file)) {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    /*
     * Customize your transformer here:
     * - Indentation
     * - Encoding
     * - ...
     */
    transformer.transform(new DOMSource(document), new StreamResult(writer));
  }
}

【讨论】:

    最近更新 更多