import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
public class JDOMTest {
public void read() throws Exception {SAXBuilder saxBuilder = new SAXBuilder();
Document document = saxBuilder.build(new File("C:\\aaa.xml"));
Element e = document.getRootElement();
List aList = e.getChildren("linkname");
for (int i = 0; i < aList.size(); i++) {
Element element = (Element) aList.get(i);
String nameString = element.getChildText("name");
String emailString = element.getChildText("email");
System.out.println(nameString);
System.out.println(emailString);
}
}
public void write() throws Exception {
Element addresslist = new Element("addresslist");
Document doc = new Document(addresslist);
for (int i = 0; i < 10; i++) {
Element linkname = new Element("linkname");
Element name = new Element("name");
Element email = new Element("email");
// 赋值
name.setText("坑爹啊!");
email.setText("yui2000@163.com");
// 建立关系
linkname.addContent(name);
linkname.addContent(email);
addresslist.addContent(linkname);
}
// 写入
XMLOutputter xmlOutputter = new XMLOutputter();
xmlOutputter.output(doc, new FileOutputStream(new File("C:\\aaa.xml")));
}
public static void main(String[] args) throws Exception {
JDOMTest jdomTest = new JDOMTest();
//jdomTest.write();
jdomTest.read();
}
}