sax解析のxpath技術詳細&Demo

6714 ワード

1.知識紹介
1.1導入
質問:dom 4 jを使用して比較的深い階層のノード(ラベル、属性、テキスト)をクエリーすると、面倒です!!!
1.2 xPath作用
主に、必要なノードオブジェクトをすばやく取得するために使用されます.
1.3 dom 4 jでのxPathテクノロジーの使用方法
1)xPathをインポートしてjarパッケージをサポートします.jaxen-1.1-beta-6.JAr 2)xpathメソッドList selectNodes(「xpath式」)を使用する.複数のノードオブジェクトNode selectSingleNode(「xpath式」)をクエリーします.ノードオブジェクトのクエリー
1.4 xPath構文
/                   xml          (      )
//                               。
*                          
[]                               
@                           
and                         (   &&)
text()                         


2.最初のxpathプログラム
/**
 *    xpath  
 *
 */
public class Demo1 {

    
    public static void main(String[] args) throws Exception{
        /**
         *   :   id  2     
         */
        Document doc = new SAXReader().read(new File("e:/student.xml"));
        
        //1.  id 2     
        //  xpath  
        Element stuElem = (Element)doc.selectSingleNode("//Student[@id='2']");

        //2.    
        stuElem.detach();
        
        //3.  xml  
        FileOutputStream out = new FileOutputStream("e:/student.xml");
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        XMLWriter writer = new XMLWriter(out,format);
        writer.write(doc);
        writer.close();
    }

}

3.xPath式構文
import java.io.File;
import java.util.List;

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

public class Demo2 {

    public static void main(String[] args) throws Exception {
        Document doc = new SAXReader().read(new File("./src/contact.xml"));
        
        String xpath = "";
        
        /**
         * 1.   /                   xml          (      )
         */
        xpath = "/contactList";
        xpath = "/contactList/contact";
        
        /**
         * 2. //                               。
         */
        xpath = "//contact/name";
        xpath = "//name";
        
        /**
         * 3. *                          
         */
        xpath = "/contactList/*"; //   contactList       
        xpath = "/contactList//*";//   contactList      (      )
        
        /**
         * 4. []                               
         */
        //  id   contact  
        xpath = "//contact[@id]";
        //    contact  
        xpath = "//contact[2]";
        //      contact  
        xpath = "//contact[last()]";
        
        /**
         * 5. @                           
         */
        xpath = "//@id"; //  id      ,    Attribute  
        xpath = "//contact[not(@id)]";//     id   contact    
        xpath = "//contact[@id='002']";//  id    002 contact  
        xpath = "//contact[@id='001' and @name='eric']";//  id    001, name   eric contact  
        
        /**
         *6.  text()           
         */
        //  name        ,  Text  
        xpath = "//name/text()";
        xpath = "//contact/name[text()='  ']";//        name  
        
        
        List list = doc.selectNodes(xpath);
        for (Node node : list) {
            System.out.println(node);
        }
    }

}


4.xpathケース:ユーザーログイン効果のシミュレーション
ユーザーログイン機能:ユーザーがユーザー名とパスワードを入力->「データベース」クエリーに対応するかどうか->「ユーザー->「はい」はログインに成功したかどうかを示す:ログインに失敗したことを示すxmlをデータベースuserとして使用する.xmlはユーザーのデータを格納するために使用されます
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

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

public class Demo3 {

    public static void main(String[] args)throws Exception{
        //1.             
        BufferedReader br = 
                new BufferedReader(new InputStreamReader(System.in));
        
        System.out.println("      :");
        String name = br.readLine();
        
        System.out.println("     :");
        String password = br.readLine();
        
        //2. “   ”           
        //     :   user.xml       
           //name    ‘    ’, password    ‘    ’ user  
        Document doc = new SAXReader().read(new File("./src/user.xml"));
        Element userElem = (Element)doc.selectSingleNode("//user[@name='" +name +"' and @password='"+password+"']");
        
        if(userElem!=null){
            //    
            System.out.println("    ");
        }else{
            //    
            System.out.println("    ");
        }
    }

}


5.xpathテクノロジーを使用して仕様htmlドキュメントを読み込む
import java.io.File;
import java.util.Iterator;
import java.util.List;

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

public class Demo4 {

    public static void main(String[] args) throws Exception{
        Document doc = new SAXReader().read(new File("./src/personList.html"));
        //System.out.println(doc);
        
        //  title  
        Element titleElem = (Element)doc.selectSingleNode("//title");
        String title = titleElem.getText();
        System.out.println(title);
        
        /**
         *   :          
         *         :
         *         :001   :     :    :18   :xxxx   : xxxx
         *         :002   :     :    :20   :xxxx   : xxxx
         *       ......
         */
        //1.     tbody  tr  
        List list = (List)doc.selectNodes("//tbody/tr");
        //2.  
        for (Element elem : list) {
            //  
            //String id = ((Element)elem.elements().get(0)).getText();
            String id = elem.selectSingleNode("td[1]").getText();
            //  
            String name = ((Element)elem.elements().get(1)).getText();
            //  
            String gender = ((Element)elem.elements().get(2)).getText();
            //  
            String age = ((Element)elem.elements().get(3)).getText();
            //  
            String address = ((Element)elem.elements().get(4)).getText();
            //  
            String phone = ((Element)elem.elements().get(5)).getText();
            
            System.out.println("  :"+id+"\t  :"+name+"\t  :"+
                                gender+"\t  :"+
                                age+"\t  :"+address+
                                "\t  :"+phone);
        }
    }
}