Recently, I am busy with some projects. I need to talk about converting a txt file into an xml file. I didn't find a good method on the Internet. I asked my brother to say that I use java and relevant jar packages, it can be done. So I tried it. And record it;
Preparations:
Import the required jar package, refer to my uploaded: http://download.csdn.net/detail/u010454729/7272571
The following is an example of using a jar package to call a function:
Import java. io. bufferedReader; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. fileReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. unsupportedEncodingException; import org. dom4j. document; import org. dom4j. incluenthelper; im Port org. dom4j. element; import org. dom4j. io. outputFormat; import org. dom4j. io. XMLWriter; public class test {public static void txt_to_xml (File file) throws FileNotFoundException {// The txt File is converted into an xml file and written into the xml File, String encoding = "UTF-8 "; inputStreamReader read; try {read = new InputStreamReader (new FileInputStream (file), encoding); BufferedReader reader = new BufferedReader (read); // some InputStream fin = New FileInputStream (file); String xml_name = file. getName (). substring (0, file. getName (). indexOf ("world"); // find the name of the corresponding file: Document document = incluenthelper. createDocument (); Element root = document. addElement ("Entity"); root. addAttribute ("title", xml_name); // root node, add attribute root. addAttribute ("type", "PER"); root. addAttribute ("id", ""); root. addAttribute ("name", xml_name); Element element = null; String text = ""; int line _ Num = 1; String file_getname = file. getAbsolutePath (); String filePath_xml = file_getname.substring (0, file_getname.indexOf (". ") + ". xml "; // output path element = root. addElement ("facts"); element. addAttribute ("class", "Infobox"); Element element_fact = null; Element element_wiki = root. addElement ("wiki_text"); Element record_ele = null; while (text = reader. readLine ())! = Null) {// System. out. println (text + "----------------------------------------" + line_num); // print each line of string to be read and check if (text. contains ("entity") | text. contains ("facts") {} else if (text. contains ("
<") {Element_fact.addAttribute (" name ", text. substring (text. indexOf ("name = \" ") + 6, text. indexOf ("\"> <");} else if (text. contains ("attr") {element_fact.addAttribute ("name", text. substring (text. indexOf ("name = \" ") + 6, text. indexOf ("attr")-2); element_fact.setText (text. substring (text. indexOf ("\"> ") + 2, text. indexOf (""); Element_id.setText (text. substring (text. indexOf (" \ ">") + 2, text. indexOf ("