2016-07-19 84 views
0

我有這段代碼(請參閱下面的內容),我想從中獲取值'Day.1'和'Day.2'。從HtmlAgilityPack獲取類標記的值

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
doc.LoadHtml("<div class=\"large-10 columns\"><div class=\"box\"><div class=\"table-header\">Day.1</div></div></div>" + 
      "<div class=\"large-10 columns\"><div class=\"box\"><div class=\"table-header\">Day.2</div></div></div>"); 

var classes = doc.DocumentNode.SelectNodes("//div[@class=\"large-10 columns\"]"); 
foreach (var item in classes) 
{ 
    var str = item.SelectSingleNode("//div[@class=\"box\"]//div[@class=\"table-header\"]"); 
    Output += "Test: " + str.InnerText.Split('.')[1] + "\n"; 
} 

利用該代碼的輸出是:

Test: 1 
Test: 1 

爲什麼變量「STR」正從第一「表頭」類兩個時間值?

+0

你爲什麼不直接去了'DIV [@class = \ 「表頭\」]'節點? – ElenaDBA

+0

當你只需要一個''/' – ElenaDBA

+0

因爲我只需要它們2個值並且'table-header'可以在HTML代碼的其他部分中找到時,你正在使用雙'''''''''''' – user1693813

回答

1

嘗試:

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
doc.LoadHtml("<div class=\"large-10 columns\"><div class=\"box\"><div class=\"table-header\">Day.1</div></div></div>" + 
        "<div class=\"large-10 columns\"><div class=\"box\"><div class=\"table-header\">Day.2</div></div></div>"); 

     var classes = doc.DocumentNode.SelectNodes("//div[@class=\"large-10 columns\"]/div[@class=\"box\"]/div[@class=\"table-header\"]"); 
     foreach (var item in classes) 
     { 
      var str = item.InnerText; 
      Output += "Test: " + str.Split('.')[1] + "\n"; 
     }