本文主要是介绍XML的创建,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这里使用的是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 blocke.printStackTrace();}}}
这篇关于XML的创建的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!