xPath对xml文档的处理入门2

我测试的环境是:WindowsXP、eclipse3.2、jdk1.6、dom4j1.6.1.jar、z-dom4j-1.4.jar

其中dom4j1.6.1.jar、z-dom4j-1.4.jar都可以在本人的资源库中进行下载,还有Dom4j的API,以及学习文档。

测试的xml文档参看:xPath对xml文档的处理入门1

package org.dom4j.document_study_XPath;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class Test_XPath {

         public static void main(String[] args) {
                readexml("C:\\1.xml");
          }
 
          //解析原始的xml
          public static void readexml(String xmlpath){
                  SAXReader readxml = new SAXReader();
                  Document doc = null;  
                  try {
                          doc = readxml.read(new File(xmlpath));//解析原始的xml
                          TestSelectNodes_01(doc);
                          TestSelectNodes_02(doc);
                          TestSelectNodes_03(doc);
                  } catch (Exception e) {
                          e.printStackTrace();
                  }
          }
          // 通过节点的XPath路径获取document某个节点的父类节点,document 一个Dom4j的Document对象
         @SuppressWarnings("unchecked")
         public static void TestSelectNodes_01(Document document) {
                  List<Node> listnode =document.selectNodes("//title");
                  System.out.println("title父节点节点:");
                  for(Node node : listnode){
                          Node fathorNode = (Node) node.selectObject("..");
                          System.out.println("节点名称name=" +fathorNode.getName() + "\t节点属性name=" + fathorNode.valueOf("@name"));
                  }
          }
          //通过节点的XPath路径获取document当前的根节点,document 一个Dom4j的Document对象
         @SuppressWarnings("unchecked")
         public static void TestSelectNodes_02(Document document) {
                  List<Node> listnode =document.selectNodes("/root");
                  System.out.println("根节点:");//其中root是根节点名称
                  for(Node node : listnode){
                          if(node.getName()!=null){
                                 System.out.println("节点名称name=" +node.getName() + "\t节点属性name=" + node.valueOf("@name"));
                           }
                   }
           }
           //通过节点的XPath路径获取document根路径下的名称为titlechild的所有子节点,document 一个Dom4j的Document对象
          @SuppressWarnings("unchecked")
          public static void TestSelectNodes_03(Document document) {
                  List<Node> listnode =document.selectNodes("/root//titlechild");
                  System.out.println("获取根节点下的所有名称为titlechild节点:");
                  for(Node node : listnode){
                          if(node.getName()!=null){
                                    System.out.println("节点名称name=" +node.getName() + "\t节点属性name=" + node.valueOf("@name"));
                           }
                   }
            }
}

你可能感兴趣的:(xPath对xml文档的处理入门2)