Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29308991
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Java

2010-07-19 21:31:58

1、XML配置文件如下

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>


2、相关的JAVA代码片段
2.1

public static void main(String[] args) {
        List firstName = new ArrayList();
        List attrs = new ArrayList();
        SAXReader saxReader = new SAXReader();
        try {
            Document doc = saxReader.read("t.xml");
            String xpathString = "bookstore/*/title";
            List list = doc.selectNodes(xpathString);
            Iterator it = list.iterator();
            while(it.hasNext()) {
                Element elt = (Element)it.next();
                System.out.println(elt.getName());
                Attribute attr = (Attribute) elt.attribute("lang");
                System.out.println(attr.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

输出:

title、eng、title、eng

介绍:bookstore/*/title 这种XPATH表达式的作用!


2.2

public static void main(String[] args) {
        List firstName = new ArrayList();
        List attrs = new ArrayList();
        SAXReader saxReader = new SAXReader();
        try {
            Document doc = saxReader.read("t.xml");
            String xpathString = "bookstore/book/*[@lang]";
            List list = doc.selectNodes(xpathString);
            System.out.println(list.size());
            Iterator it = list.iterator();
            while(it.hasNext()) {
                System.out.println("a");
                Element elt = (Element)it.next();
                System.out.println(elt.getName());
                Attribute attr = (Attribute) elt.attribute("lang");
                System.out.println(attr.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


阅读(1004) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~