2012-03-31 42 views
0

我無法看到我的xpath邏輯出錯。使用xpath導航到XML部分

這裏是我正在處理的一個更大的xml部分。 (注意使用HTML敏捷性包IM)

<div> 
    <div></div> 
    <span class="pp-headline-item pp-headline-phone"> 
     <span class="telephone" dir="ltr"> 
      <nobr>(732) 562-1312</nobr> 
      <span class="pp-headline-phone-label" style="display:none">()</span> 
     </span>&#8206; 
    </span> 
    <span> &middot; </span> 
    <span class="pp-headline-item pp-headline-authority-page"> 
     <span> 
      <a href="http://maps.google.com/local_url?q=http://www.fed.com/q=07746+pizza"> 
       <span>fed.com</span> 
      </a> 
     </span> 
    </span> 
</div> 

我的目標是從XML的這些塊,我用

.SelectNodes("//div/span['pp-headline-item pp-headline-phone']/../..") 

這個走出主XML文件中提取各種數據點我期望得到上面列出的所有部分,所以我可以迭代他們,並提取像網站,手機,地址的東西...

問題是當我迭代這個節點集我不能得到我想要的數據點,就好像節點集不是上面列出的節點集。

我的邏輯是從頂級div提取節點集到nodset中,並在迭代到xpath到我想要的數據點時。

我不喜歡這樣寫道:

foreach (HtmlNode n in BuizRowsgoogMaps) 
       {      
        //get phone number 
        if (n.SelectSingleNode("span/nobr").InnerHtml != null) 
        { 
         strPhone = n.SelectSingleNode("span/nobr").InnerHtml; 

         //get phone site 
         strSite = n.SelectSingleNode("//span['pp-headline-item pp-headline-authority-page']/span/a/span").InnerHtml; 
        } 
       } 

我懷疑我的XPath不齧合在一起得到我想要的東西,但是當我確認我表達我得到想要的結果......我用這個來驗證我的想法它的工作讓我陷入了困境:

//div/span['pp-headline-item pp-headline-phone']/../../span['pp-headline-item pp-headline-phone']/span/nobr 

回答

1

你的代碼幾乎是正確的,你只需要修改你的xpath一下。

foreach (HtmlNode n in BuizRowsgoogMaps) 
{ 
    //get phone number 
    if (n.SelectSingleNode(".//span/nobr").InnerHtml != null) 
    { 
    strPhone = n.SelectSingleNode(".//span/nobr").InnerHtml; 

    //get phone site 
    strSite = n.SelectSingleNode(".//span['pp-headline-item pp-headline-authority-page']/span/a/span").InnerHtml; 
    } 
} 

.//告訴xpath匹配當前節點而不是根目錄。