2011-01-31 16 views
0

PHP - このXMLたDOMのXpath質問

<?xml version="1.0" encoding="UTF-8" ?> 
<databases> 
    <default> 
     <type>mysql</type> 
     <host>localhost</host> 
     <table-prefix></table-prefix> 
     <username>root</username> 
     <password></password> 
     <charset>UTF-8</charset> 
    </default> 
    <test> 
     <type>mysql</type> 
     <host>localhost</host> 
     <table-prefix></table-prefix> 
     <username>root</username> 
     <password></password> 
     <charset>UTF-8</charset> 
    </test> 
</databases> 

コード:

public function get($xpath = '/') 
    { 
     $dom_object = new DOMDocument(); 
     $dom_object->load($this->_filename); 
     $domxpath_object = new DOMXpath($dom_object); 

     $domnodelist_object = $domxpath_object->query($xpath); 

     return $this->XMLConfigurationToArray($domnodelist_object); 
    } 

private function XMLConfigurationToArray(DOMNodeList $domnodelist_object) 
    { 
     $configuration_array = array(); 

     foreach ($domnodelist_object as $element) 
     { 
      if ($element->hasChildNodes()) 
      { 
       foreach ($element->childNodes as $c) 
       { 
        print_r('<pre>' . $element->tagName . '</pre>'); 
       } 
      } 
     } 

     return $configuration_array; 
    } 

それはデータベース5回をプリントアウトなぜ?私はget( '/ databases')を呼び出します... ありがとうございます。

+0

"データベース"が2回表示されると思われますか? –

+0

データベースは一度だけ間違っていますか? – thomas

+1

*(関連)* http://stackoverflow.com/questions/4598409/printing-content-of-a-xml-file-using-xml-dom/4599724#4599724 – Gordon

答えて

1

すぎのchildNodesある空白、(textNodes)もあります

textNodesを無視:

if($c->nodeType===1) 
{ 
    echo('<pre>' . $c->tagName . '</pre>'); 
} 

を...または子(要素)-nodesを取得するためにもXPATHを使用しています。

また、(ゴードンによってリンクのトピックで説明したように)最初から空白を無視することができます。

$dom_object = new DOMDocument(); 
$dom_object->preserveWhiteSpace=false; 
+0

あなたはタブ==空白を意味しますか?だから、xmlでは、私は空白を持つことができません?すべての空白がテキストノードになりますか?ありがとうございました。 – thomas

+0

はい、タブ、改行、スペース。 「」の後に1つ、「」の後に1つ、「」の後に1つがあります。 –

+1

@thomas:いいえ、すべてのテキストノードはテキストノードになります。空白のみのテキストノードの保存または削除は、通常、問題またはXMLパーサの設定です。 [@ Gordonの答え]を確認してください(http://stackoverflow.com/questions/4598409/printing-content-of-a-xml-file-using-xml-dom/4599724#4599724) –

1

それはデータベース5回をプリントアウトなぜ? I コールのget(「/データベース」)

databasesトップ要素は5人の子供を持つためには、ノード:2つの要素と要素を囲む3(空白のみ)テキストノードを、。