package com.bjsxt.util; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** * Use Jdom to write a XML file * <selects> * <select> * <id>1</id> * <name>北京</name> * </select> * <select> * <id>2</id> * <name>上海</name> * </select> * <selects> */ public class TestJdom { public static void main(String[] args)throws IOException, FileNotFoundException { new TestJdom().testXMLWrite(); } public void testXMLWrite()throws IOException, FileNotFoundException { //先New一个根。在Jdom中每一个节点都是Element Element rootElt = new Element("selects"); Element selectElt11 = new Element("select"); Element idElt11 = new Element("id"); Element valueElt11 = new Element("name"); idElt11.addContent("1"); valueElt11.addContent("北京"); selectElt11.addContent(idElt11); selectElt11.addContent(valueElt11); Element selectElt22 = new Element("select"); Element idElt22 = new Element("id"); Element valueElt22 = new Element("name"); idElt22.addContent("2"); valueElt22.addContent("上海"); selectElt22.addContent(idElt22); selectElt22.addContent(valueElt22); rootElt.addContent(selectElt11); rootElt.addContent(selectElt22); //将根rootElt作为参数。相当于得到了整个的XML文件 Document doc = new Document(rootElt); //设定输出的XML文件编码,默认生成的XML文件为UTF-8编码 XMLOutputter out = new XMLOutputter(); out.setFormat(Format.getCompactFormat().setEncoding("UTF-8")); //在控制台上打印输出XML System.out.println(out.outputString(doc)); //将生成的XML文件写到D:/testXML.xml中 out.output(doc, new FileOutputStream("D:/testXML.xml")); } }
Use Jdom to Write XML file
最新推荐文章于 2026-01-05 17:06:32 发布
本文介绍了一个使用Java JDOM库来创建XML文件的例子。通过构造XML元素并将其添加到根节点,最终输出到文件中。该过程展示了如何构建XML结构,并设置文件编码。
582

被折叠的 条评论
为什么被折叠?



