请教,如何用JDOM 生成下面格式的XML文件?最好能有代码!小弟感谢不尽!<?xml version="1.0" encoding="utf-8"?>
<photos path="images/">
<photo name="" url="1.jpg">This is the optional description for photo 1</photo>
<photo name="" url="2.jpg">This is the optional description for photo 2</photo>
<photo name="" url="3.jpg">This is the optional description for photo 3</photo>
<photo name="" url="4.jpg">This is the optional description for photo 4</photo>
<photo name="" url="5.jpg">This is the optional description for photo 5</photo>
<photo name="" url="6.jpg">This is the optional description for photo 6</photo>
<photo name="" url="7.jpg">This is the optional description for photo 7</photo>
<photo name="" url="8.jpg">This is the optional description for photo 8</photo>
<photo name="" url="9.jpg">This is the optional description for photo 9</photo>
</photos>

解决方案 »

  1.   

    Element rootElement = new Element("photos");
    Document myDocument = new Document(rootElement);//创建指定根节点的xml文档rootElement.setAttribute("path","images");//为根节点添加属性Element photoElement1 = new Element("photo"); //创建元素节点
    photoElement1.setAttribute("name","");//为元素添加属性
    photoElement1.setAttribute("url","1.jpg");//为元素添加属性
    photoElement1.addContent("This is the optional description for photo 1");//为元素添加文本节点
    rootElement.addContent(photoElement1);//把第一个photo元素添加到跟节点下//....剩下的8个元素的方法省略,跟photoElement1 类似。
     XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());//有空白变化,即有缩进xmlOut.output(myDocument,System.out);//把整个xml对象输出到控制台FileWriter writer = new FileWriter("c:/myFile.xml");//下面三行代码是创建xml文件到硬盘
    xmlOut.output(myDocument, writer);
    writer.close();剩下的8个我省略了,你跟着photoElement1 的做就行了