-2
このコードは別のスレッドに投稿されていましたが、テキストファイルをxmlに正しくサブフォーマットするように変換することはできません。むしろ出力よりもこのことから、単純なXMLテキストファイルをxmlに変換する方法
:これに
Example One
Example Two
Example Three
:へ
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"?>
<inserts>
<option>Example One</option>
<option>Example Two</option>
<option>Example Three</option>
</inserts>
私は、テキストファイルから、次の変換が必要に
<?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();
}
}
感謝を。
はあなたにBhargavをありがとう - 私はこれを試してみましょう – Ltaylor