使用xpath搜索元素

xpath.html
<!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=UTF-8">
<title>jQuery.get()</title>
<style type="text/css">
ul{border:1px solid black;list-style:none;
margin:0pt;padding:0pt;float:left;
font-family:Verdana,Arial,Helvetica,sans-serif;
font-size:12px;width:300px;}
li{padding:10px 5px;border-bottom:1px solid black;}
</style>
</head>
<body>
<input type="button" value="SHow all books" id="all" />
<input type="button" value="SHow stories with quotes" id="total" />

<input type="button" value="Get last book" id="last" />

<input type="button" value="Books with year < 1900" id="year" />


<p id="result"></p>
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
    
     $('input:button').click(function(){
          $.get('xpath.php',
          {action:$(this).attr('id')},
          function(data){
               $('#result').html(data);
              
          }
          );
         
     });

}
);

</script>
</body>
</html>
xpath.php
 
<?php
$objxml=simplexml_load_file('../common.xml');
if(!$objxml){
     echo "error loading xml";
}else{
     $response='';
    
     $action=$_GET['action'];
     switch ($action)
     {
          case 'all':
               $book=$objxml->xpath('//book/name');
               $response.='<ul>';
               foreach($book as $item){
                    $response.='<li>';
                    $response.=$item[0].'('.$item['year'].')</li>';
               }
               $response.='</ul>';
               break;
          case 'total':
               $stories=$objxml->xpath('//story');
               $response.='<ul>';
               foreach($stories as $story){
                    $response.='<li>';
                    $response.='<label>'.$story->title.'</label>
                    <br /><em>'.$story->quote.'</em></ul>';
               }
               $response.='</ul>';
               break;
          case 'last':
               $book=$objxml->xpath('//book[last()]');
               echo '<strong>'.$book[0]->name.'('.$book[0]->name['year'].')</strong>';
               break;
          case 'year':
               $book=$objxml->xpath('//book/name[@year<1990]');
               $response.='<ul>';
               foreach($book as $item){
                    $response.='<li>';
                    $response.=$item[0].'('.$item['year'].')</li>';
               }
               $response.='</ul>';
               break;
     }
     echo $response;
}
posted @ 2014-04-04 17:26  wint  Views(235)  Comments(0)    收藏  举报