import java.io.FileWriter; import java.io.IOException; import org.jdom2.*; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class XMLWriterExample { public static void main(String[] args) { try { Document document = new Document(); Element root = new Element("books"); document.setRootElement(root); Element book1 = new Element("book"); book1.setAttribute("id", "1"); book1.addContent(new Element("title").setText("Java Programming")); book1.addContent(new Element("author").setText("John Doe")); Element book2 = new Element("book"); book2.setAttribute("id", "2"); book2.addContent(new Element("title").setText("Python Basics")); book2.addContent(new Element("author").setText("Jane Smith")); root.addContent(book1); root.addContent(book2); XMLOutputter xmlOutput = new XMLOutputter(); Format format = Format.getPrettyFormat(); xmlOutput.setFormat(format); FileWriter writer = new FileWriter("books.xml"); xmlOutput.output(document, writer); writer.close(); } catch(IOException e) { e.printStackTrace(); } } } <books> <book id="1"> <title>Java Programming</title> <author>John Doe</author> </book> <book id="2"> <title>Python Basics</title> <author>Jane Smith</author> </book> </books>


上一篇:
下一篇:
切换中文