public static void updateXML(String filePath) throws Exception { SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(new FileInputStream(filePath));//读入文件 Element root = doc.getRootElement(); //得到根元素 // Element e = root.getChild("occupation"); // System.out.println(e.getText()); // System.out.println(e.getName()); // System.out.println(e.getAttributeValue("dynasty"));//获取元素属性值 // e.setText("大皇帝"); List li = root.getContent();//全部内容:子元素、注释、文本等 List list = root.getChildren(); //只有标记内容 System.out.println(li.size()); System.out.println(list.size()); Element ele = (Element) list.get(0); System.out.println(ele.getText()); //将doc写入到某一个xml文件中,从而更新硬盘中的文件 // XMLOutputter xmlOut = new XMLOutputter(); // xmlOut.output(doc, new FileOutputStream(filePath)); }
//须要导入jdom.jar包 public static void createXML() throws Exception { Element root = new Element("resume"); Element name = new Element("name"); Element preName = new Element("preName"); Element occupation = new Element("occupation"); Element preOccupation = new Element("preOccupation"); Attribute attr = new Attribute("dynasty", "唐朝"); occupation.setAttribute(attr); name.setText("李世明"); preName.addContent("秦王"); preOccupation.addContent("将军"); occupation.addContent("皇帝"); root.addContent(name); root.addContent(preName); root.addContent(occupation); root.addContent(preOccupation); Document doc = new Document(root); Format format = Format.getPrettyFormat(); //Format format = Format.getCompactFormat(); format.setEncoding("utf-8"); //<?xml version="1.0" encoding="utf-8"?> XMLOutputter xmlOutputter = new XMLOutputter(format); xmlOutputter.output(doc, new FileOutputStream("f:/1.xml")); }