2014-02-20 38 views
2

我試圖做的是我有一段下面列出的html代碼。我需要錨標記中的內容。HtmlAgilityPack:獲取字符串內的錨標記內容的問題

HtmlDocument newHtml = new HtmlDocument(); 
newHtml.OptionOutputAsXml = true; 

var content = "<div class="business-name-container"> 
      <span class="tier_info"></span> 
       <h3 class="title fn org"> 
        <a  href="http://www.abc.com/nationwide/mip/xyz?lid=161004592" class="url link">Foo</a> 
       </h3> 
      </div>"; 

newHtml.Load(content); 
HtmlNode doc = newHtml.DocumentNode; 
var findContent = doc.SelectNodes("//a[@class='url link']"); 
foreach (var aContent in findContent) 
{ 
    if (acontent.InnerHtml != null) 
    { 
      Console.WriteLine("Content: " + acontent.InnerHtml); 
    } 
} 

但我沒有得到結果。 我想輸出是 「內容:富」

回答

2

更換

Console.WriteLine("Content: " + acontent.InnerHtml); 

隨着

Console.WriteLine("Content: " + acontent.InnerText); 

甚至更​​好像這樣

var result = acontent.DocumentNode 
      .Descendants("a") 
      .Where(x=>x.Attributes["class"].Value =="url link").InnerText; 
+0

現在我在newHtml.Load(content)行中出現錯誤「路徑中的非法字符」; 是必要將字符串轉換爲HtmlDocument?我們不能直接從字符串中獲取數據嗎? – pkdq

+0

你正在使用的HTML敏捷包,因此,這就是我的答案使用.. –

+0

抱歉扎克米沒有得到錯誤的地方。實際上,在C#中新增了一個,而在我現在要去哪裏的項目中,我感到困惑。仍然感謝你的時間和幫助。非常感謝扎克。 – pkdq