import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
public class JDOM01 {
public static void main(String[] args) {
Element student=new Element("student");
Attribute id=new Attribute("id","001"); // 属性节点
Attribute aa=new Attribute("aa","xx");
student.setAttribute(id);
student.setAttribute(aa);
Element name=new Element("name"); //元素节点名
name.setText("张三"); // 设置文本节点
student.addContent(name);
Document document=new Document(student);
XMLOutputter out=new XMLOutputter();
out.setFormat(out.getFormat().setEncoding("UTF-8"));
try {
out.output(document,new FileOutputStream("src/student2.xml"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
public class JDOM02 {
public static void main(String[] args) throws Exception{
SAXBuilder builder=new SAXBuilder(); // SAXBuilder
Document document=builder.build("src/students.xml");
Element students=document.getRootElement();
List studentList=students.getChildren("student");
for(int i=0;i<studentList.size();i++){
Element student=(Element)studentList.get(i);
String id=student.getAttributeValue("id");
String name=student.getChildText("name");
String sex=student.getChildText("sex");
String age=student.getChildText("age");
System.out.println("学号:"+id+";姓名:"+name+";性别:"+sex+";年龄:"+age);
}
}
}