public static void main(String[] args) throws Exception { SAXBuilder sb = new SAXBuilder(); // 新建立构造器 Document doc = sb.build(new FileInputStream("company.xml")); // 读入文件 Element root = doc.getRootElement(); // 获得根元素element List row = root.getChildren(); //取得节点列表 //按CID查找直接定位到ROW元素返回的是集合 List find = XPath.selectNodes(root, "/ROOT/ROW[@PID=´1´]"); for (int i = 0; i < find.size(); i++) { Element findelement = (Element) find.get(i); System.out.PRintln(findelement.getAttributeValue("CNAME")); }
//多条件查询 Element findelement=(Element)XPath.selectSingleNode(root,"/ROOT/ROW[@PID=´3´][@CID=´10´]"); System.out.println(findelement.getAttributeValue("CNAME"));
XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat()); //格式华输出,产生缩进和换行
//重新格式化 Format format = outp.getFormat(); format.setEncoding("GB2312"); format.setExpandEmptyElements(true); outp.setFormat(format);
//outp.output(doc, new FileOutputStream("jdomcompany.xml")); //输出XML文档 outp.output(doc, System.out); System.out.println("JDOM操作XML文档完毕!"); } }