(四)使用JDOM读、写xml文件
JDOM=DOM修改文件的优点+SAX读取快速的优点 // 1.生成xml文件 import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.output.XMLOutputter; public static void main(String[] args) { Element addresslist = new Element("addresslist"); // 定义根节点 Element linkman = new Element("linkman"); // 定义节点名称 Element name = new Element("name"); // 定义节点名称 Element email = new Element("email"); // 定义节点名称 Attribute id = new Attribute("id", "mxzer"); // 定义属性 Document document = new Document(addresslist); // 定义一个Document对象 name.setText("mxzer"); // 设置元素内容 email.setText("mxzer3200@123.com"); name.setAttribute(id); // 设置name元素的属性 linkman.addContent(name); // 设置linkman的子节点 linkman.addContent(email); addresslist.addContent(linkman); // 将linkman加入根节点下 XMLOutputter out = new XMLOutputter(); // 输出xml文件 out.setFormat(out.getFormat().setEncoding("GBK")); // 设置输出编码 try { out.output(document, new FileOutputStream("e:" + File.separator+ "jdom2.xml")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } 2.解析xml文件 /** * 在JDOM中,所有节点都是以集合的形式返回的,集合中的每一个对象都是Element实例. * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // 1.建立SAX解析 SAXBuilder builder = new SAXBuilder(); // 2.找到Document文档 Document dc = builder.build("e:" + File.separator + "jdom2.xml"); // 3.读取根元素 Element stu = dc.getRootElement(); // 得到全部的linkman子元素 List list = stu.getChildren("linkman"); for (int x = 0; x < list.size(); x++) { // 输出 Element ele = (Element) list.get(x); // 取出每一个子元素 String name = ele.getChildText("name"); // 取得name元素的内容 String id = ele.getChild("name").getAttribute("id").getValue(); // 取得name元素的id属性 String email = ele.getChildText("email"); System.out.println("联系人信息:"); System.out.println("姓名:" + name + ", id:" + id); System.out.println("邮箱:" + email); System.out.println("------------------------------"); } }
Author