2012-08-10 73 views
-2

一個節點出現的次數我有以下格式的XML文件: -查找一個xml文件

<EticketCanStatusRes> 
     <ETicket> 
      <eticketno>asdf4511</eticketno> 
      <flightuid>57490</flightuid> 
      <passuid>91832</passuid> 
      <PnrNumber>AADS12</PnrNumber> 
      <Origin>COK</Origin> 
      <Destination>DEL</Destination> 
     </ETicket> 
     <ETicket> 
      <eticketno>asdf4511</eticketno> 
      <flightuid>57490</flightuid> 
      <passuid>91832</passuid> 
      <PnrNumber>AADS12</PnrNumber> 
      <Origin>COK</Origin> 
      <Destination>DEL</Destination> 
     </ETicket> 
</EticketCanStatusRes>'; 

我需要找出多少<ETicket>元素有。在我的例子也有2

+0

你如何試圖做到這一點? – Fluffeh 2012-08-10 11:09:57

回答

0

您可以使用simplexmlxpath

$string = '<EticketCanStatusRes> 
     <ETicket> 
      <eticketno>asdf4511</eticketno> 
      <flightuid>57490</flightuid> 
      <passuid>91832</passuid> 
      <PnrNumber>AADS12</PnrNumber> 
      <Origin>COK</Origin> 
      <Destination>DEL</Destination> 
     </ETicket> 
     <ETicket> 
      <eticketno>asdf4511</eticketno> 
      <flightuid>57490</flightuid> 
      <passuid>91832</passuid> 
      <PnrNumber>AADS12</PnrNumber> 
      <Origin>COK</Origin> 
      <Destination>DEL</Destination> 
     </ETicket> 
</EticketCanStatusRes>'; 

$xml = new SimpleXMLElement($string); 
$result = $xml->xpath('//ETicket'); 
echo count($result); // 2 
0

如果你想探微關於沒有相對限制只有一種類型的節點統計,DOM的getElementsByTagName ::就足夠了,因爲它返回具有「長度」只讀屬性的DOMCollection。

$document = new DOMDocument; 
$document->load("your file.xml"); 
echo $document->getElementsByTagName('tagname')->length; 

如果你想提供更多的限制,你可以使用XPath用SimpleXML像@Arkh說,或DOM文檔。

0

我把在同一目錄下的XML文件,PHP文件,因此,該代碼是這樣的

 <?php 
$dom = new DOMDocument; 
// load the XML string defined above 
$dom->load('tiket.xml'); 


$etickets = $dom->getElementsByTagName('ETicket'); 
$count = 0; 

foreach ($etickets as $etiket) { 
    $count++; 
} 

echo $count; 
?>