- 步骤
1.通过DocumentHelper生成一个Document对象
2.添加根元素
3.为根元素添加子元素
4.为某个元素添加属性,(可有可无)
5.给某个元素添加子元素(这个可以迭代完成)
6.给子元素添加文本信息
7.将Document对象的内容输出到一个文件中,并命名为XML文件,
package bjsxt.xml; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class WriteXML { public static void main(String[] args) throws IOException { //使用DocumentHelper创建一个Document对象 Document doc = DocumentHelper.createDocument(); //添加并得到根元素 Element root = doc.addElement("books"); //为根元素添加子元素 Element book = root.addElement("book"); //为子元素添加属性 book.addAttribute("id", "b01"); //为book添加子元素 Element name = book.addElement("name"); Element author = book.addElement("author"); Element price = book.addElement("price"); //为子元素添加文本信息 name.addText("Think in Java"); author.addText("MIKE"); price.addText("20.5"); //将Document对象的内容写入到一个文件中 Writer write = new FileWriter(new File("src/book1.xml")); doc.write(write); //关闭流 write.close(); } }
运行结果:
<?xml version="1.0" encoding="UTF-8"?> <books><book id="b01"><name>Think in Java</name><author>MIKE</author><price>20.5</price></book></books>
由于以上结果的结构是不太美好,所以在输出到文件中的过程中需要修改,即以下代码
package bjsxt.xml; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.sql.SQLException; import javax.sql.RowSetInternal; import javax.sql.rowset.WebRowSet; import javax.sql.rowset.spi.XmlWriter; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class WriteXML { public static void main(String[] args) throws IOException { //使用DocumentHelper创建一个Document对象 Document doc = DocumentHelper.createDocument(); //添加并得到根元素 Element root = doc.addElement("books"); //为根元素添加子元素 Element book = root.addElement("book"); //为子元素添加属性 book.addAttribute("id", "b01"); //为book添加子元素 Element name = book.addElement("name"); Element author = book.addElement("author"); Element price = book.addElement("price"); //为子元素添加文本信息 name.addText("Think in Java"); author.addText("MIKE"); price.addText("20.5"); /*//将Document对象的内容写入到一个文件中 Writer write = new FileWriter(new File("src/book1.xml")); doc.write(write); //关闭流 write.close(); */ //格式良好地输出 OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter write = new XMLWriter(new FileWriter(new File("src/book2.xml")),format); write.write(doc); //关闭流 write.close(); } }
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="b01">
<name>Think in Java</name>
<author>MIKE</author>
<price>20.5</price>
</book>
</books>