【发布时间】:2016-06-29 06:01:20
【问题描述】:
我在另一个线程上看到了此代码,但无法将其转换为正确格式的文本文件,以使用子元素转换为 xml。而不是输出一个简单的xml
从这里:
Example One
Example Two
Example Three
到这里:
<?xml version="1.0" encoding="UTF-8"?>
<inserts>
<option>Example One</option>
<option>Example Two</option>
<option>Example Three</option>
</inserts>
我需要从文本文件进行以下转换:
first_main_elem
f_child_elem1:one
f_child_elem2:two
second_main_elem
s_child_elem1:one
s_child_elem1:two
third_standalone_element: null value
fourth_element:stand alone
到:
<?xml version="1.0" encoding="UTF-8"?>
<first_main_elem>
<f_child_elem1>one</f_child_elem1>
<f_child_elem1>two</f_child_elem1>
<f_child_elem1>three</f_child_elem1>
</first_main_element>
<second_main_elem>
<s_child_elem1>one</s_child_elem>
<s_child_elem2>two</s_child_elem2>
</second_main_elem>
<fourth_standalone_elem/>
<fifth_element>stand alone</fifth_element>
贴出的代码:
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();
}
}
感谢您对此提出任何建议或意见。
【问题讨论】: