使用JDOM操作XML系列文章四 使用JDOM和XPATH结合查询
package jing.xml;
/**
* <p>Title: 使用JDOM和XPATH结合查询</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author 欧朝敬 13873195792
* @version 1.0
*/
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import org.jdom.xpath.*;
import Java.io.*;
import java.util.*;
public class TreeXML {
public TreeXML() {
}
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文档完毕!");
}
}