javaweb学习总结十(xml解析<SAX以及DOM方式>)

一:XML解析技术

一般我们使用sun公司或者开源组织开发的工具包解析xml效率比较高。

 

1:jaxp解析xml,jaxp是sun公司开发的解析xml工具包

2:jaxp解析xml代码如下

a:获取document文档树对象

 1 @Test
 2     // 获取document对象
 3     public void test1() throws Exception {
 4         // 1:获取解析工厂对象
 5         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 6         // 2:获取解析对象
 7         DocumentBuilder builder = factory.newDocumentBuilder();
 8         // 3:获取document对象
 9         Document doc = builder.parse("xml/books.xml");
10         System.out.println(doc);
11     }
 1     // 获取document对象方法
 2     private Document getDoc() throws Exception {
 3         // 1:获取解析工厂对象
 4         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 5         // 2:获取解析对象
 6         DocumentBuilder builder = factory.newDocumentBuilder();
 7         // 3:获取document对象
 8         Document doc = builder.parse("xml/books.xml");
 9         return doc;
10     }

 

b:获取元素节点

1 @Test
2     // 获取xml中的元素内容
3     public void test2() throws Exception {
4         Document doc = getDoc();
5         NodeList lists = doc.getElementsByTagName("name");
6         Node node = lists.item(0);
7         System.out.println("名称:" + node.getNodeName() + "\n内容:"
8                 + node.getTextContent());
9     }

c:递归遍历xml文件中所有节点

 1 @Test
 2     // 遍历所有的节点 递归
 3     public void test3() throws Exception {
 4         Document doc = getDoc();
 5         Node node = doc.getElementsByTagName("bookstore").item(0);
 6         list(node);
 7     }
 8 
 9     private void list(Node node) {
10         if (node instanceof Element) {
11             System.out.println(node.getNodeName());
12         }
13         NodeList list = node.getChildNodes();
14         for (int i = 0; i < list.getLength(); i++) {
15             list(list.item(i));
16         }
17     }

d:获取元素属性

1 @Test
2     // 获取元素属性
3     public void test4() throws Exception {
4         Document doc = getDoc();
5         Element element = (Element) doc.getElementsByTagName("book").item(0);
6         String name = element.getAttribute("name");
7         System.out.println("name:" + name);
8     }

如果Node节点对象的方法比较少是,可以使用子类Element的方法。

 

posted @ 2016-08-06 20:42  warrior1234  阅读(215)  评论(0编辑  收藏  举报