文本文件到xml转换java [英] text file to xml conversion java
本文介绍了文本文件到xml转换java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有文本文件,我想将其转换为 Java 中的 XML 文件:用java读取文件,然后转成xml.
I have text file and I want to convert this in to a XML file in java: Read the file in java and then convert in to xml.
Contact
Arun_niit
Arun_niit
nura_e@yahoo.co.in
Contact
Contact
Bống MũnHải
Hải Anh Bống Mũn
http://www.facebook.com/profile.php?id=689849077
Contact
我希望按以下顺序输出:
I want the output in the following order:
<contact>
<Firstname>Arun_niit</Firstname>
<Secondname>Arun_niit</Secondname>
<Email>nura_e@yahoo.co.in</Email>
</contact>
<contact>
<Firstname>Bống MũnHải</Firstname>
<Secondname>Hải Anh Bống Mũn</Secondname>
<URL>http://www.facebook.com/profile.php?id=689849077</URL>
</contact>
请帮帮我示例代码将不胜感激.
Please help me guys & sample codes will be highly appreciated.
这是正确的做法吗,请...[代码]
Is this correct way of doing it, please... [code]
import java.io.*;
import java.io.ObjectInputStream.GetField;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import java.util.Scanner;
public class Item {
private String Name;
private String LName;
private String Email;
public static void main (String args[]) {
public static void readFile(File file)
{
Scanner freader = new Scanner("D:/juin17.part");
String line = null;
while (freader.hasNextLine()) {
line = freader.nextLine();
if(line==contact){
Item item = new item();
item.Name =freader.nextLine();
item.LName =freader.nextLine();
item.Email =freader.nextLine();
freader.nextLine();
}
itemList.add(item);
}
freader.close();
}
FileOutputStream fos = new FileOutputStream(info.file);
OutputFormat of = new OutputFormat("XML","windows-1250",true);
of.setIndent(1);
of.setIndenting(true);
ContentHandler hd = serializer.asContentHandler();
hd.startDocument();
AttributesImpl atts = new AttributesImpl();
hd.startElement("","",info.category,atts);
for (int i=0;i<itemList.size();i++)
{
atts.clear();
Item temp = new Item();
temp = itemList.get(i);
hd.startElement("","","FirstName",atts);
hd.characters(temp.Name.toCharArray(),0,temp.Name.length());
hd.endElement("","","FirstName");
hd.startElement("","","LastName",atts);
hd.characters(temp.LName.toCharArray(),0,temp.LName.length());
hd.endElement("","","LastName");
hd.startElement("","","Email",atts);
hd.characters(temp.mail.toCharArray(),0,temp.mail.length());
hd.endElement("","","EMail");
}
hd.endElement("","",info.category);
hd.endDocument();
fos.close();
}
}
推荐答案
这里 是使用 DOM 创建 xml 的示例我认为您可以更改它以适合您自己的目的.
here is an example of creating an xml using DOM i think you can alter it to fit your own purposes.
如果您只想从文本创建一个 xml,我认为它比使用 SAX 更简单
if all that you want is to create an xml from text i think it will be simpler than using SAX
希望这会有所帮助.
这篇关于文本文件到xml转换java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文