这里使用的是org.dom4j的jar包来完成xml格式数据的创建。
import java.io.IOException;
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class XMLUtil {
public static void main(String[] args) {
Document doc = DocumentHelper.createDocument();
Element books = doc.addElement("books");
Element book = books.addElement("book");
book.addElement("bookname").setText("Thinking in java");
book.addElement("version").setText("第4版");
book.addElement("author").setText("Bruce Eckel");
book.addElement("publish").setText("Prentice Hall");
Element book1 = books.addElement("book");
book1.addElement("bookname").setText("spring in action");
book1.addElement("version").setText("第3版");
book1.addElement("author").setText("沃尔斯 (Craig Walls)");
book1.addElement("publish").setText("人民邮电出版社");
OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("UTF-8");
format.setIndent(false);
format.setNewlines(false);
format.setNewLineAfterDeclaration(false);
StringWriter sw = new StringWriter();
XMLWriter xw = new XMLWriter(sw, format);
try {
xw.write(doc);
xw.close();
System.out.println(sw.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}