日期:2014-05-18  浏览次数:20841 次

救急 关于JDOM生成XML的问题
小弟使用JDOM   生成一个XML   文件中间有一个标签如 <BNIF   seqno= "1 "> 这样,后面是一个属性   标识该字段在本文件中的编号   如seqno= "1 ",seqno= "2 ",seqno= "3 "这样,请各位大大指点这个属性用JDOM   的什么方法写入     完成就结帖

------解决方案--------------------
addAttribute( "属性名 ", "值 ") ;
------解决方案--------------------
Jdom的用法:
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class StudentDAO {
String file;//xml文件的位置
FileOutputStream fo;
Document doc;
SAXBuilder builder = new SAXBuilder();
Format format; //用于设置xml文件的格式
private StudentDAO() {
}
//构造函数中设置file和format
public StudentDAO(String webroot) {
file = webroot + "/data/student.xml ";
format = Format.getPrettyFormat();
format.setIndent( " ");
format.setEncoding( "utf-8 ");
}
//向xml文件中添加一条记录
public boolean add(StudentInfo si) {
String id = si.getId();
boolean idAlreadyExisted = false;
boolean addResult = false;
Element root;
List allStudent;
try { doc = builder.build(file);
root = doc.getRootElement();
allStudent = root.getChildren();
//检查要添加的信息是否存在
for (int i = 0; i < allStudent.size(); i++) {
Element element = (Element) allStudent.get(i);
if (element.getChild( "id ").getText().equals(id)) {
idAlreadyExisted = true;
break;
}
}
//向xml文件中添加新的信息,并返回true
if (!idAlreadyExisted) {
Element student = new Element( "student ");
student.addContent(new Element( "id ").setText(si.getId()));
student.addContent(new Element( "name ").setText(si.getName()));
student.addContent(new Element( "birthday ").setText(si
.getBirthday()));
student.addContent(new Element( "address ").setText(si
.getAddress()));
allStudent.add(student);
XMLOutputter xout = new XMLOutputter(format);
fo = new FileOutputStream(file);
xout.output(doc, fo);
return true;
}

} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
}
return addResult;
}
//从xml文件中删除一条信息
public boolean del(String id) {
boolean delResult = false;
Element root;
List allStudent;
try {
doc = builder.build(file);
root = doc.getRootElement();
allStudent = root.getChildren();
for (int i = 0; i < allStudent.size(); i++) {
Element student = (Element) allStudent.get(i);
//如果id存在,则删除些条信息,并返回true
if (student.getChild( "id ").getText().equals(id)) {
allStudent.remove(i);
XMLOutputter xout = new XMLOutputter(format);
fo = new FileOutputStream(file);
xout.output(doc, fo);
return true;
}
}

} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch