2012-09-20 52 views
0

我正在使用PHP中的sax,因爲我解析用於更新數據庫的xml文件大約爲150MB。如何判斷我在xml對象中的哪個位置

我無法理解如何判斷我在使用sax的xml對象中的位置。例如在XML看起來是這樣的:

<listing> 
    <home> 
     <address>123 main st.</address> 
    </home> 
    <brokerage> 
     <address>555 N. high st.</address> 
    </brokerage> 
</listing> 

使用SAX,我知道上市標記開始時,和家庭的標籤,然後將地址標記等,但隨後控制傳遞給我設定的功能用xml_set_character_data_handler和我可以得到的地址。

我的問題是要知道我是否正在閱讀首頁 - >地址或經紀 - >地址。

此xml文件中有多個字段共享相同的標籤名稱,並且在不同的父標籤(firstName,lastName,phone,email等等,作爲listingAgent,propertyContact等下的子項)下多次使用。

我一直在搜索,但我找到的唯一sax示例顯示如何回顯數據,而不是如何根據xml文件中的數據作出決定。有沒有我不知道的函數,還是必須編寫我自己的函數來確定孩子屬於哪個父元素?

回答

1

你可以檢查使用簡單堆疊XML文檔中你的位置,存儲打開標籤(僞)的列表:

$openedTags = array(); 

while ($node = /* read next XML node*/) { 
    if ($node->isOpeningTag()) { 
     array_push($openedTags, $node->getTagName()); 
     continue; 
    } 

    if ($node->isClosingTag()) { 
     array_pop($openedTags); 
     continue; 
    } 

    if ($node->isTextNode()) { 
     print_r($openedTags);  // root ... listing, home, address 
     echo $node->getTextValue(); // 123 main st. 
    } 
} 
+0

我會嘗試一下你的方法。這似乎是最好的方式去。我真的很驚訝,還沒有一個內置的功能。 – rmmoul

相關問題