XML XPATH解析

首先导包:
dom4j-1.6.1.jar
jaxen-1.1-beta-6.jar
代码

public class XPATHTest {
    public static void main(String[] args) throws Exception {
        base();

    }
    public static void base() throws Exception {
        Document doc = new SAXReader().read(new File("./src/test/stu.xml"));
        String xpath = "";
        /**
         *  /      绝对路径   表示从xml的根位置开始或子元素(一个层次机构)
         *  //     相对路径   表示不分任何层次结构的选择元素
         *  *           通配符      表示匹配所有元素
         *  []     条件          表示选择什么条件下的元素
         *  @      属性        表示选择属性节点
         *  text()  表示选择文本内容
         *  
         *  Element ele = (Element) doc.selectSingleNode(xpath);//得到一个
            System.out.println(ele.getName());
         */
        xpath = "/Students";//得到Students标签      
        xpath = "/Student/student";//得到Students标签下的student标签

        xpath = "//student"; //得到xml中的所有student标签
        List<Element> ele = doc.selectNodes(xpath);//得到所有
//      // System.out.println(ele.getName());
//      for(Element e : ele){
//          System.out.println(e.getName());
//      }

        xpath = "/student/*";//得到student标签下的所有子标签
        xpath = "/student//*";//得到student标签下的所有标签(不分层次)



        xpath = "//student[2]";//得到第二个student标签
        xpath = "//student[last()]";//得到最后一个student标签

        xpath = "//@id";//选择id属性节点对象,返回Attribute对象
        xpath = "//student[@id]";//得到带有id属性的标签
        xpath = "//student[@id='2']";//得到id属性值为2的标签


        xpath = "//name/text()"; //选择name标签下的文本内容,返回Text对象
        xpath = "//name[text()=='张三']";//得到name标签的文本内容为张三的name标签



    }

    public static void test1() throws Exception {
        Document doc = new SAXReader().read(new File("./src/test/stu.xml"));
        //使用XPATH技术查询id=2的学生标签
        Element ele = (Element) doc.selectSingleNode("//student[@id='2']");
        ele.detach();//删除标签
        FileOutputStream out = new FileOutputStream("D:/stu.xml");
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(out,format);
        writer.write(doc);
        writer.close();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值