2015-11-05 100 views
0

在服務器上,我通過客戶端JS的AJAX將字符串作爲字符串取回。內容是一個嵌套的DIV,帶有ul,li項目。 HTML DIv snippet使用Xpath或HtmlAgilityPack獲取字符串中的嵌套節點

<div> //please see link above 
     <ul class="tree" id="ulID" name="input"> 
      <li><span class="vertical..."></span> 
       <div></span>1</div> 
       <ul>.. 
</div> 

我使用C#HtmlAgilityPack,但我沒能獲得嵌套內容的提取數據,並添加回數據。

下面是一些代碼。

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument(); 

// nested 
htmlDoc.OptionFixNestedTags=true; 

bool failed = false; 

// Use: htmlDoc.LoadHtml(htmlString); 

// ParseErrors is an ArrayList 
if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0) 
{ 
    // Handle any parse errors as required 
    // check if string was JSON formatted 
    if (htmlDoc.LoadHtml(JSONdeserialize(htmlString)).ParseErrors.Count() > 0) failed = true; 
} 
else 
{ 

    if (htmlDoc.DocumentNode != null) 
    { 
     HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//ulID"); 

     if (bodyNode != null) 
     { 
      // **how can I get the contents of the node here??**** 
      // what is the xpath to get all the structured contents so I can walk the tree 
      // If option walk tree 
      // How can I build foreach(HTMLnode node in nodes) nested array 
     } 
    } 
} 
  1. 什麼是XPath來選擇在DOM字符串的所有內容,當我沒有身體,但簡單Div enclosed string
  2. 如何提取所有節點及其嵌套級別的內容
  3. 有關如何保存此結構的任何建議?所以我可以輕鬆恢復它?

回答

1

我不確定您現在擁有的Xpath是否正確。 我也不確定何時第一個ul標籤結束。如果它在div關閉之前結束。然後你可以使用這個xpath。

"//ul[@id='ulID']" 

然後你得到第一個ul htmlnode。然後你可以迭代它的孩子。 我強烈建議你看看xpath examples

+0

這是給我所有的UL項目,我怎麼走這個a)所有項目,b)只有'li'項目,或者只是目標'div項目下面我做了這個「// ul [@id ='ulID'] // li「但沒有爲li項目工作 – everest

+1

在此xpath之後:」// ul [@ id ='ulID']「您有一個HtmlNode。你可以打電話。 bodyNode.ChildNodes - 獲取所有子節點的HtmlNodeCollection。在foreach循環中,如果(htmlNode.OriginalName ==「li」)可以用if表達式對它們進行排序。 –

+0

這會給我一個像列表一樣的字典,或者我如何保留層次嵌套? – everest

相關問題