2012年5月17日 星期四

PHP登入-使用 Bootstrap 美化

以下程式碼基於PHP研習中的實作練習下的管理者登入。

1. 先建立一個”admin”資料庫,並建立” manager”資料表,資料表中新增三欄位分別為「idno」”(主索引)、「 id」 char(12)、「pwd」 char(12)。

2. 在config.php內設定資料庫環境。
<?php
//======資料庫變數======//
$cfgDB_HOST = 'localhost';  //資料庫所在主機位置
$cfgDB_PORT ="3306";        //資料庫PORT(預設為3306)
$cfgDB_USERNAME ="hebe";    //資料庫帳號
$cfgDB_PASSWORD ="12345";   //資料庫密碼
$cfgDB_NAME = "admin";      //使用的資料庫
?>

3. connect.php插入config.php用來連結資料庫,並下選擇資料庫的指令。
<?php
// 建立資料庫連線
function create_connection()
{
    include 'config.php';
    $link = mysql_connect($cfgDB_HOST . ":" . $cfgDB_PORT, $cfgDB_USERNAME, $cfgDB_PASSWORD);
    return $link;
}

// 選擇資料庫
function execute_sql($cfgDB_NAME, $sql, $link)
{
    mysql_select_db($cfgDB_NAME, $link);
    $result = mysql_query($sql, $link);
    return $result;
}
?>

4. login.php為使用介面,以post方式送出。
(該範例使用Boostrap美化,使用過程可參考: Asp.net 的基本使用)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>  
    <meta http-equiv="Content-Type" content="text/html; charset=big5">
    <link rel="stylesheet" type="text/css" href="bootstrap.css" /> 
</head>
<body>
<div class="span4" >
    <form action="check.php" method="post" > 
        <table class="table table-bordered"  >
            <tr>
                <th colspan="2">管理者登入</th>
            </tr>
            <tr>
                <td> 帳 號 </td>
                <td><input type="text" name="id"></td>
            </tr>
            <tr>
                <td> 密 碼 </td>
                <td><input type="password" name="pwd"></td>
            </tr>
            <tr>
                <td colspan="2">
                <input type="submit" value="登入" class="btn btn-primary"></td>                        
            </tr>
        </table>      
    </form> 
</div>
</body>
</html>

5. check.php將login.php傳來兩欄位”id”及” pwd”值加以判斷帳密是否正確,若登入成功會以session方式暫存帳號並顯示於畫面中。
<?php 
//連結資料庫
    session_start();
    require_once("connect.php");
    $link = create_connection();
    $id = $_POST["id"]; //login.php傳來帳號欄位輸入值
    $pwd = $_POST["pwd"]; //login.php傳來密碼欄位輸入值
    $sql  =  "select id from manager where id='$id' and pwd='$pwd'";
    $rs   =  execute_sql("admin", $sql, $link);
    $total=   mysql_num_rows($rs);  
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>  
    <link rel="stylesheet" type="text/css" href="bootstrap.css" /> 
</head>
<body>
    <div class="span4" >
    <?php   
        //判斷所選取資料的數目是否大於0,若大於0則表示資料庫有這筆帳號和密碼,即登入成功
        if($total>0){
           $_SESSION['username'] = $id; 
           echo "歡迎" . $_SESSION['username'] . "登入成功!<br/>";
           echo '<a class="btn btn-danger btn-small" href="logout.php">登出</a>';
        } 
        
        else{ 
           echo "帳號或密碼輸入有誤,請再重試一次!<br/>";
           echo '<a class="btn btn-info btn-small" href="logout.php">返回</a>';
        }
    ?>   
    </div>
</body>
</html>

6. logout.php登出,清除session值。
<?php session_start(); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
//將session清空
unset($_SESSION['username']);
echo '登出中......';
echo '<meta http-equiv=REFRESH CONTENT=1;url=login.php>';
?>

完成圖


回 PHP 目錄
回首頁

2012年5月12日 星期六

PHP上傳檔案 - 使用 Boostrap 美化

這次小女子我來分享PHP上傳檔案的方法啦~~就請大家參考參考一下羅~ :D

以下程式碼基於PHP 研習中的實作練習下的檔案上傳程式碼。

1.

於config.php設定存放檔案的資料夾及檔案限制大小。
(須先自行於同目錄下建立"uploads"資料夾哦~)
<?php
//存放檔案的資料夾,這裡我是開一個「uploads」的資料夾來存放上傳的檔案。// 
$cfg_path =  "uploads/";

//上傳檔案大小限制,可根據自己的需求來作修改//
$cfg_max_size = 2*1024*1024;
?>    

2.

work.php以_FILES函數處裡文件上傳,並用move_uploaded_file()函數將資料上傳至指定資料夾中,其中還包含了上傳後的檔案命名。
<?php
include ("config.php");  //插入config.php

     //如果檔案上傳有錯誤,可以顯示錯誤代碼。
    if ($_FILES['upfile']['error'] > 0)
    {
        echo "Error: " . $_FILES['upfile']['error'] . "<br />"; 
    }
    else
    {
        //上傳檔案的原始名稱。
        $upfile_name = $_FILES['upfile']['name']; 
     //上傳的檔案原始大小。
        $upfile_size = $_FILES['upfile']['size']; 
     //上傳的檔案類型。
        $upfile_type = $_FILES['upfile']['type']; 
        //上傳檔案後的暫存資料夾位置。
        $upfile_tmp_name = $_FILES['upfile']['tmp_name'];  
    }
    
    //==== 檢查是否確實有上傳檔案 ====//     
    if($upfile_size==0){       
?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=big5">
    </head>
    <body>
        <script language=javascript>
            alert("請確實選擇要上傳的檔案喔!");
            history.go(-1);  //返回
        </script>             
    </body>
</html>   
 <?php
 }

    //檢查上傳的檔案是否有超過限制的大小
    if($upfile_size>$cfg_max_size){          
?>
<html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=big5">
    </head>
    <body>
    <script language="javascript">
      alert("上傳檔案的大小不得超過 <? echo $cfg_max_size /1024/1024 ?> MB,\n請您重新上傳!");
      history.go(-1);                               
    </script>   
    </body>
</html>                             
<?php
    exit;
    }
    
    $yearDir = date("Y");
    $monthDir = date("m");
    $dayDir = date("d");
    
    $full_path = "$cfg_path" . "$yearDir/$monthDir/$dayDir/";
    $year_path = "$cfg_path" . "$yearDir/";
    $month_path = "$cfg_path" . "$yearDir/$monthDir/";
    
    //判定是否有建立"年","月","日" 資料夾,若沒有就建立資料夾
    if(!is_dir($year_path)) 
        mkdir($year_path);
    
    if(!is_dir($month_path))
        mkdir($month_path);
        
    if(!is_dir($full_path))
        mkdir($full_path);
    
    /*
    explode(separator,string,limit)
    separator     必需。規定在哪里分割字串。
    string     必需。要分割的字串。
    limit     可選。規定所返回的數組元素的最大數目。
    "a.b.c.d.png" => $file_name = abcd
                => $file_subname = png
    array[] {"a", "b", "c", "d", "png"} count = 5
    */
    $file_arr = explode(".", $_FILES['upfile']['name']);
    $file_subname = $file_arr[count($file_arr) - 1]; //副檔名
    
    $file_name = ""; 
    for ($i = 0; $i < count($file_arr) - 1; $i ++ )
        $file_name .= $file_arr[$i];
    
    //上傳後檔案命名
    $upfile_name = $file_name . '-' . date("His") . '.' . $file_subname; 
    
    //====== 檔案上傳至資料夾 =====//                 
    $cp = move_uploaded_file($upfile_tmp_name, "$full_path/$upfile_name");
            
        
    //判斷是否上傳成功
    if($cp)
    {
        echo "Upload Success!<br>";
        echo "檔案大小:".$upfile_size."<br>";
        echo "檔案名稱:".$upfile_name;                  
    }
    else
 {
        echo "Fail!";                   
    }              
?> 

3.

可至Apache資料夾下的bin資料夾中找到php.ini檔,將其date.timezone = UTC改成date.timezone = "Asia/Taipei",此動作是將時間改成台灣的標準時間,修改後將伺服器重新啟動即可。

4.

upload.php為使用介面程式碼,其中我為了美化整體畫面套用了Boostrap,你可至bootstrap 網站下載相關.css及.js檔。 ( 使用過程可參考:Bootstrap 於 Asp.net 的基本使用)
<?php
include ("config.php"); //插入config.php
?>
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=big5">
    <link rel="stylesheet" type="text/css" href="bootstrap.css" /> 
    <script language="javascript">
    function checkform()
    {    
        if(document.thisform.upfile.value=='')
        {
            alert('您還沒選擇要上傳的檔案喔!')
            return false;
        }
        return true;
    }
    </script>
    </head>
    <body>
    <br><br>
    <center>
    <form action="work.php" method="post" enctype="multipart/form-data" name="thisform">
    ※上傳檔案大小以 <font color=red><?php echo $cfg_max_size/1024/1024; ?></font> MB 為限<br>
    <table ><tr><td>
    <table class="table table-striped table-bordered table-condensed">
      <tr>
        <td> 選擇檔案 </td>
        <td> <input type="file" name="upfile" class="input-file" size="20" /></td>
      </tr>
      <tr>
         <td>  
           <input type="hidden" name="work" value="upload" />
           <input type="submit" value="確定送出" onclick="return checkform()" class="btn btn-primary" />
         </td>
      </tr>
    </table>
    </td></tr></table>
    </form>
    </body>
</html> 


完成圖



回 PHP 目錄
回首頁



2012年5月10日 星期四

PHP 換頁 - 使用 Bootstrap 美化


大家好,我是一個將邁入社會的小姑娘,這幾天對PHP有了一點點小小的研究,那就是當你需要顯示大量資料時,畫面資料一大堆不知道該怎麼辦,此時可以用 PHP 換頁 的方式將資料分成好幾頁,以方便使用者閱讀。以下是我所適用的方法,希望對大家有所幫助~YA!!

以下程式碼基於 PHP 研習 中的實作練習下的資料換頁程式碼。

1. 

首先請至 Northwind for mysql 下載微軟範例資料庫北風 (northwind) 資料庫作為 PHP 換頁 的顯示資料,並將其匯入phpmyadmin中。




2. 

接著在config.php內設定資料庫環境。

<?php
    //======資料庫變數======//
    $cfgDB_HOST = 'localhost';     //資料庫所在主機位置
    $cfgDB_PORT ="3306";          //資料庫PORT(預設為3306)
    $cfgDB_USERNAME ="trista";    //資料庫帳號
    $cfgDB_PASSWORD ="trista";    //資料庫密碼
    $cfgDB_NAME = "northwind";    //使用的資料庫
?>


3. 

connect.php插入config.php用來連結資料庫,並下選擇資料庫的指令。

<?php
    // 建立資料庫連線
    function create_connection()
    {
        include 'config.php';
        $link = mysql_connect($cfgDB_HOST . ":" . $cfgDB_PORT, $cfgDB_USERNAME, $cfgDB_PASSWORD);
        return $link;
    }
    // 選擇資料庫
    function execute_sql($cfgDB_NAME, $sql, $link)
    {
        mysql_select_db($cfgDB_NAME, $link);
        $result = mysql_query($sql, $link);
        return $result;
    }
?>

4.

 
為了美化 PHP 換頁 整體畫面可至bootstrap 套用相關.css.js檔。
( 使用過程可參考:Bootstrap 於 Asp.net 的基本使用,如果還不會用,你們自己想辦法 )

5.

 
PHP 換頁範例中插入了connect.php連結資料庫,並以bootstrap美化畫面(我所使用的包含bootstrap.cssbootstrap-responsive.css),資料庫則是以北風資料庫做為範例。

<?php 
    // 資料庫連結
    require_once("connect.php");  
    $link=create_connection();  

    // 判斷Page傳來指定的頁數,以決定本頁顯示的資料
    if (isset($_POST['page']))
        $nowPage = $_POST['page'];
    
    if (!isset($nowPage)) 
        $nowPage = 1;

    // 判斷pern傳來的值,以決定顯示的資料筆數
    if (isset($_POST['pern']))
        $perNum = $_POST['pern'];
    
    if (!isset($perNum)) 
        $perNum = 5;  // 每頁顯示 5 筆(每次取5筆資料)
  
    //總筆數
    $sql = "select count(*) from nwsuppliers "; // 計算資料表 nwsuppliers 總筆數
    $rs = execute_sql("northwind", $sql, $link);  // 選擇資料庫 northwind
      list($totalNum) = mysql_fetch_row($rs);
  
    //若資料庫中無任何資料
    if($totalNum == 0)
    {
        echo "目前沒有資料";
        exit;
    }
  
    //開始起始指標
    $startId = ($nowPage - 1)* $perNum;
  
    //該頁實際顯示資料筆數目
    if(($startId+$perNum)>$totalNum) {
        $realPerNum = $totalNum - $startId;
    }else{
        $realPerNum = $perNum;
    }
  
    //總頁數
    if($totalNum % $perNum == 0){
        $totalPage = $totalNum / $perNum;
    }else{
        $totalPage = intval($totalNum / $perNum)+1;
    }
  
    //第一頁
    $firstPage=1;
  
    //最後一頁
    $lastPage = $totalPage;  
  
    //上一頁
    if($nowPage > 1){
        $forwardPage = $nowPage - 1;
        $firstPgLink = "<li><a href=\"javascript:chg(1, $perNum);\">第一頁</a></li>";
        $forPgLink = "<li><a href=\"javascript:chg($forwardPage, $perNum);\">《  </a></li>";
    }else{
        $forwardPage = false;
        $firstPgLink = "";
        $forPgLink = "";
    } 

    //下一頁
    if($nowPage < $totalPage){
        $nextPage = $nowPage + 1;
        $lastPgLink = "<li><a href=\"javascript:chg($lastPage, $perNum);\">最後一頁</a></li>";
        $nextPgLink = "<li><a href=\"javascript:chg($nextPage, $perNum);\"> 》 </a></li>";
    }else{  
        $nextPage =  false;
        $nextPgLink = "";
        $lastPgLink = "";
    }

?>
<!DOCTYPE html>
<html>
<head>
    <link type="text/css" rel="stylesheet" href="css/bootstrap.css">
        <script language="JavaScript">
            function chg(np, n){
                document.sd.page.value=np;
                document.sd.pern.value=n;
                document.sd.submit();
            }
        </script>
</head>
<body>
    <form action="page.php" method="post" name="sd">
        <input type="hidden" name="page"> 
        <input type="hidden" name="pern">   
    </form>

    <table class="table table-striped table-bordered table-condensed" align='center' >
        <tr align='center' > 
            <td nowrap width='80' >CompanyName </td> 
            <td nowrap width='100' >ContactName</td>
            <td nowrap width='100' >ContactTitle</td>
        </tr>
        <?php
            //取出資料欄位CompanyName , ContactName , ContactTitle
            $sql = " select  CompanyName ,  ContactName,  ContactTitle  from nwsuppliers ";
            $rs = execute_sql("northwind", $sql, $link);

            //顯示資料
            for($i=$startId;$i<$startId+$realPerNum;$i++){
                mysql_data_seek($rs,$i);
                list( $CompanyName ,  $ContactName, $ContactTitle ) = mysql_fetch_row($rs);
        ?>
        <tr align='center'>
            <td nowrap ><?php echo $CompanyName ;?></td>
            <td nowrap ><?php echo $ContactName;?></td>
            <td nowrap ><?php echo $ContactTitle;?></td>    
        </tr>
        <?php } ?>
    </table>
  
    <form>
        <div class="pagination pagination-centered">
        <ul>
            <?php echo $firstPgLink; //第一頁 ?> 
            <?php echo $forPgLink; //上一頁 ?>
            <?php 
                $limitPage = 2; //顯示該頁+-頁碼數
                $minPage = $nowPage - $limitPage < 1 ? 1 : $nowPage - $limitPage; //顯示最小頁碼
                $maxPage = $nowPage + $limitPage > $totalPage ? $totalPage : $nowPage + $limitPage; //顯示最大頁碼

                //顯示換頁頁碼
                for($x = $minPage ; $x <= $maxPage ; $x++)
                {
                    $li = "<li>";
                    if ($x == $nowPage)
                        $li = "<li class=\"active\">";
                    $PgLink = $li . "<a href=\"javascript:chg($x, $perNum);\">$x</a></li>";
                    echo $PgLink;
                }
            ?>
   
            <?php echo $nextPgLink; //下一頁 ?>
            <?php echo $lastPgLink; //最後一頁 ?>
            <li><a>共<?php echo $totalPage; //總頁數 ?>頁</a></li>
            <li><a>(<?php echo $totalNum; //總資料筆數 ?> 筆資料)</a></li>
            <li><a style="border-style: none;">
            <?php 
                if($totalPage == 1){ 
                    echo "";
                }
                //快速換頁下拉式選單
                else{     
                    $pageFast="<select name=\"pageFast\" onChange=\"chg(this.form.pageFast.value, this.form.perNum.value);\" style=\"width: 90px;\" >";
                    for($i=1;$i<=$totalPage;$i++){
                        $pageFast.="<option value=\"".$i."\"";
                    if($i==$nowPage) $pageFast.=" selected";
                    $pageFast.=">第".$i."頁</option>";        
                }             
                $pageFast.="</select>";
                echo $pageFast;
                }
            ?>       
                </a>
            </li>
            <li><a style="border-style: none;">

            <?php
     
                if ($totalPage == 1)
                {
                    $pagePerNum = "<select name=\"perNum\" onChange=\"chg(1, this.form.perNum.value);\" style=\"width: 110px;\" >";
                }
                else
                {
                    $pagePerNum = "<select name=\"perNum\" onChange=\"chg(this.form.pageFast.value, this.form.perNum.value);\" style=\"width: 110px;\" >";
                }
                $pnList = array(5, 10, 20, 50, 100, 200); //每頁所顯示的資料筆數
                $pnCount = count($pnList);
    
                //下拉式顯示資料筆數
                for ($i = 0; $i < $pnCount; $i ++)
                {
                    $pagePerNum .= "<option value=\"" . $pnList[$i] . "\"";
                    if($pnList[$i] == $perNum) $pagePerNum .= " selected";
                    $pagePerNum .= ">顯示" . $pnList[$i] . "筆</option>";    
                }
     
                $pagePerNum .= "</select>";
     
                echo $pagePerNum;
            ?>      
                </a>
            </li>
        </ul>
        </div>    
    </form>   
</body>
</html>

完成圖

回 PHP 目錄
回首頁



2012年5月7日 星期一

Jquery 子母頁面間的 json 參數傳遞

應某位聽眾請求,他需要了解如何在「母頁面開啟子頁面後,子頁面處理資料後,傳遞 json 資料給母頁面接收」,稍微寫了一下,其實不難,但是由於本人眼力似乎趨近於老人,所以變數錯了過了很久才發現,差不多弄了兩個小時才把它弄好,實際上,只需要 10 分鐘。

1.

首先先到 JQuery 官方網站下載最新的 js 檔 (目前版本為:v1.7.2)

2.

再到 rahul 網友發布的網誌 jQuery - Encode & Decode arbitrary objects to and from JSON 中,擷取他的 json 編碼與解碼的 js 檔案

3.

接著我寫兩個頁面,a.html 將 b.html 打開後,將 email 與 password 欄位輸入值後,點擊「確認」鍵後,即將這兩個欄位藉由 $.JSON.encode 函式將欄位值打包為 json 格式,再利用 window.opener 的屬性將 json 格式資料傳回 a.html 的 jsonstring 隱藏欄位,再呼叫 a.html 的 javascript 的函式將 jsonstring 隱藏欄位值讀取出並放入所在位置,這麼一來,問題就解決了

  • a.html


    <html>
    <head>
    
    
    <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
    
    <script type="text/javascript">
        function show()
        {
            var encoded = $('#jsonstring').val();
            var obj = jQuery.parseJSON(encoded);
            
            $('#email').val(obj.email);
            $('#password').val(obj.password);
        }
    </script>
    </head>
    <body onload="abc();">
        <form name="form">
            <input type="text" id="email" name="email"/>
            <input type="text" id="password" name="password"/>
            
            <input type="hidden" id="jsonstring" name="jsonstring" />
            <br />
            <a href="b.html" target="_blank">b.html</a>
        </form>
    </body>
    </html>
  • b.html



    <html>
    <head>
    
    
    <script type="text/javascript" src="jquery-1.7.2.min.js" ></script>
    <script type="text/javascript" src="json2.js" ></script>
    
    <script type="text/javascript">
        function dosubmit(){
    
            var email = $('#email').val();
            var password = $('#password').val();
    
            var thing = {email: email, password: password};
    
            var encoded = $.JSON.encode(thing);  
    
            var decoded = $.JSON.decode(encoded);
    
            $('#jsonstring').val(encoded);
            window.opener.document.all.jsonstring.value = encoded;
            
            window.opener.show();
            
            this.close(); 
    
        }
    </script>
    
    </head>
    <body>
            <input type="text" id="email" name="email" />
            <input type="text" id="password" name="password" />
            <input type="button" onclick="dosubmit()" value="確認">
    
    </body>
    </html>

回JQuery目錄
回html目錄
回首頁


PHP 程式設計筆記目錄

  1. 架設 xoops 網站
  2. PHP.ini 的上傳檔案限制
  3. httpd.conf 中文說明
  4. PHP 換頁 - 使用 Bootstrap 美化
  5. PHP上傳檔案 - 使用 Boostrap 美化
  6. PHP登入-使用 Bootstrap 美化
  7. Mysql 出現亂碼的處理方式


2012年5月3日 星期四

Xpath 語法 - 使用 HtmlAgilityPack 於 C#

XPath即為XML路徑語言(XML Path Language),它是一種用來確定XML文檔中某部分位置的語言。

XPath基於XML的樹狀結構,提供在資料結構樹中找尋節點的能力。起初 XPath 的提出的初衷是將其作為一個通用的、介於XPointer與XSL間的語法模型。但是 XPath 很快的被開發者採用來當作小型查詢語言。

引用 & 參考:XPath 語言XPath AxesXML Path Language (XPath)

XPATH 基本語法

  • para selects the para element children of the context node

    para 選擇 para 子元素的本文節點


  • * selects all element children of the context node

    * 選擇所有子元素的本文節點


  • text() selects all text node children of the context node

    text() 選擇所有 text 子結點的本文節點


  • @name selects the name attribute of the context node

    @name 選擇所有 name 屬性的本文節點


  • @* selects all the attributes of the context node

    @* 選擇所有屬性的本文節點


  • para[1] selects the first para child of the context node

    para[1] 選擇所有第一個 para 元素的本文節點
  • para[last()] selects the last para child of the context node

    para[last()]選擇所最後一個 para 元素的本文節點


  • */para selects all para grandchildren of the context node

    */para 選擇所有 para 子孫的本文節點


  • /doc/chapter[5]/section[2] selects the second section of the fifth chapter of the doc

    /doc/chapter[5]/section[2] 選擇 doc 下的第五個 chapter 下的第二個 section 節點


  • chapter//para selects the para element descendants of the chapter element children of the context node

    chapter//para 選擇所有的父節點為chapter元素的para元素


  • //para selects all the para descendants of the document root and thus selects all para elements in the same document as the context node

    //para 選擇所有為 para 元素
  • //olist/item selects all the item elements in the same document as the context node that have an olist parent

    //olist/item 選擇所有父節點為 olist 元素的 item 元素


  • . selects the context node

    . 選擇當前節點


  • .//para selects the para element descendants of the context node

    .//para
  • 選擇當前節點的所有 para 子元素
  • .. selects the parent of the context node

    .. 選擇當前節點的父節點


  • ../@lang selects the lang attribute of the parent of the context node

    ../@lang 選擇名為 lang 的所有属性


  • para[@type="warning"] selects all para children of the context node that have a type attribute with value warning

    para[@type="warning"] 選擇所有 title 元素,且這些元素擁有值為 warning 的 lang 属性


  • para[@type="warning"][5] selects the fifth para child of the context node that has a type attribute with value warning

    para[@type="warning"][5] 選擇所有 title 元素,且這些元素擁有值為 warning 的 lang 属性的第五個節點


  • para[5][@type="warning"] selects the fifth para child of the context node if that child has a type attribute with value warning

    para[5][@type="warning"] 選擇所有 title 元素的第五個節點,且這個元素擁有值為 warning 的 lang 属性


  • chapter[title="Introduction"] selects the chapter children of the context node that have one or more title children with string-value equal to Introduction

    chapter[title="Introduction"] 選擇所有 chapter 元素,且其中的 title 元素的值等於 Introduction


  • chapter[title] selects the chapter children of the context node that have one or more title children

    chapter[title] 選擇所有 chapter 元素,且其中有 title 元素的值


  • employee[@secretary and @assistant] selects all the employee children of the context node that have both a secretary attribute and an assistant attribute


    employee[@secretary and @assistant] 選擇所有 employee 元素,且其中有 assistant 和 secretary 屬性的元素



XPATH 座標軸

  • ancestor 選擇當前節點的所有先輩(父、祖父等)
  • ancestor-or-self 選擇當前節点的所有先辈(父、祖父等)以及當前節點本身
  • attribute 選擇當前節點的所有屬性
  • child 選擇當前節點的所有子元素
  • descendant選擇當前節點的所有後代元素(子、孫等)
  • descendant-or-self 選擇當前節點的所有後代元素(子、孫等)以及當前節點本身
  • following 選擇文檔中當前節點的结束標籤之後的所有節點
  • namespace 選擇當前節點的所有命名空間節點
  • parent 選擇當前節點的父節點
  • preceding 選擇文檔中當前節點的開始標籤之前的所有節點
  • preceding-sibling 選擇當前節點之前的所有同级節點
  • self 選擇當前節點

使用範例

要擷取某些節點,必須要先觀察節點的獨特性質,或者是共通屬性,我通常都是使用 firefox 的外掛來觀察,IE 和 chrome 都有這種元件。
這次的例子我們在 google 上輸入 xpath,想要擷取前 10 筆網頁的標題,就先觀察它的網頁結構。

可以利用上面解說的方法,依照網頁結構來擷取,在程式中寫入以下 C# 程式碼:
HtmlWeb web;
HtmlDocument doc;
HtmlNodeCollection nodes;
string xp_title = string.Empty;


web = new HtmlWeb();
doc = web.Load("http://www.google.com/search?hl=en&q=xpath&oq=XPath");

xp_title = @"//h3[@class=""r""]";
nodes = doc.DocumentNode.SelectNodes(xp_title);

foreach (HtmlNode node in nodes)
{
    Console.WriteLine(node.InnerText);
}

執行結果如下:

比起 regular expression 輕鬆的是,它是以網頁結構去擷取,而 regular expression 是依照匹配字串做比對,所以在比對上 regular expression 比較有難度。
但是,在特殊情況下,還是需要利用 regular expression 做精密的解析。


回C#目錄
回首頁