我是个菜鸟,因为我以前没有任何 Java 编程知识。
话虽如此,我已经设法将一些代码安排到一个工作的 txt 到 xml 转换器中。
请特别注意以下注意事项:
我对代码的构建一无所知,将其视为从不同页面查找每一部分并将其合并在一起的人,不是一点,而是很多帮助。在报告这个问题之前提醒一下。谢谢
给定以下代码:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
public class xml{
static class Bean {
int id;
String firstname;
String lastname;
String mail;
public Bean(int id, String firstname, String lastname, String mail) {
super();
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.mail = mail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}
private XStream xstream = new XStream();
public static void main(String[] args) throws IOException {
new xml().process();
}
private void process() throws FileNotFoundException, IOException {
xstream.alias("item", Bean.class);
BufferedReader br = new BufferedReader(new FileReader("\\test.txt"));
try {
String line = br.readLine();
line = br.readLine();
while (line != null) {
String[] split = line.split("\t");
Bean bean = new Bean(new Integer(split[0]), split[1], split[2], split[3]);
createBeanFile(bean);
line = br.readLine();
}
} finally {
br.close();
}
}
private void createBeanFile(Bean bean) throws IOException {
BufferedWriter bw = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream("\\test.xml"),"UTF-8"));
String str = xstream.toXML(bean);
bw.write(str);
bw.close();
}
}
我如何以及在哪里添加根元素以修改我的当前输出:
<item>
<id>56885</id>
<firstname>LYTF</firstname>
<lastname>LPRT</lastname>
<mail>LYTF_LPRT@DERP.COM</mail>
</item>
对此:
<root>
<item>
<id>56885</id>
<firstname>LYTF</firstname>
<lastname>LPRT</lastname>
<mail>LYTF_LPRT@DERP.COM</mail>
</item>
</root>