用Java将TXT转XML的简单例子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23951132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:20:42  来源:igfitidea点击:

A simple example of TXT to XML with Java

javaxml

提问by Kurtiss

I have a simple text file displaying data within a list like format (input.txt).

我有一个简单的文本文件,在类似格式的列表中显示数据 (input.txt)。

Example One
Example Two
Example Three
...

What I want to do is use Java to convert this text file into an XML file (output.xml) stating that for each list entry, put it in a tag (such as <tag>Example One</tag>for example). I've researched into this, however the results I get are either irrelevant to what I am doing, over-complicates this simple example, or just doesn't provide enough explanation on what I need to do or how the provided solution works.

我想要做的是使用 Java 将此文本文件转换为 XML 文件 (output.xml),声明对于每个列表条目,将其放入标记中(<tag>Example One</tag>例如)。我已经对此进行了研究,但是我得到的结果要么与我正在做的事情无关,要么使这个简单的例子过于复杂,要么只是没有对我需要做什么或提供的解决方案如何工作提供足够的解释。

Can someone help me with what I am trying to accomplish?

有人可以帮助我完成我想要完成的任务吗?

Many thanks.

非常感谢。

采纳答案by Kurtiss

There, reads text file (data.txt) and makes it into an XML file (data.xml):

在那里,读取文本文件 (data.txt) 并将其转换为 XML 文件 (data.xml):

import java.io.*;

import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.sax.*;

public class ToXML {

    BufferedReader in;
    StreamResult out;
    TransformerHandler th;

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

    public void begin() {
        try {
            in = new BufferedReader(new FileReader("data.txt"));
            out = new StreamResult("data.xml");
            openXml();
            String str;
            while ((str = in.readLine()) != null) {
                process(str);
            }
            in.close();
            closeXml();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void openXml() throws ParserConfigurationException, TransformerConfigurationException, SAXException {

        SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        th = tf.newTransformerHandler();

        // pretty XML output
        Transformer serializer = th.getTransformer();
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        th.setResult(out);
        th.startDocument();
        th.startElement(null, null, "inserts", null);
    }

    public void process(String s) throws SAXException {
        th.startElement(null, null, "option", null);
        th.characters(s.toCharArray(), 0, s.length());
        th.endElement(null, null, "option");
    }

    public void closeXml() throws SAXException {
        th.endElement(null, null, "inserts");
        th.endDocument();
    }
}

From this:

由此:

Example One
Example Two
Example Three

To this:

对此:

<?xml version="1.0" encoding="UTF-8"?>
<inserts>
    <option>Example One</option>
    <option>Example Two</option>
    <option>Example Three</option>
</inserts>

Credit goes to the author of this post. Why can't examples be this simple?

感谢这篇文章的作者。为什么例子不能这么简单?

回答by Sanjeev

For this simple thing read your file line by line and apply transformation to the line and write to output.xml, something like this:

对于这个简单的事情,逐行读取您的文件并将转换应用于该行并写入 output.xml,如下所示:

Open File for reading
Open File for writing.

Loop through Input file {
   String str = <read a line from file>;
   str= str.replaceAll("(.*)","<tag></tag>");
   Write this string to target file.
}

Flush output file.
Close Output file.
Close Input File.

Hope this helps you in right direction.

希望这可以帮助您朝着正确的方向前进。