C# - 公共字符串仅存储集合外的最后一个值

时间:2017-03-23 18:21:44

标签: c# html-agility-pack

我正在使用HtmlAgilityPack查找网站上所有产品,颜色和产品链接。我希望能够通过在我的应用程序中输入名称和颜色来在网站上找到一个项目。

到目前为止,我的工作是: 应用程序仅使用项目名称查找项目,并使用该名称返回网站上的最后一项内容。有多个产品具有相同的名称,但每个产品都有不同的颜色。

当包含颜色时会出现问题,因为它位于不同的XPath中,因此它存储在不同的集合中。

这是我的代码:

HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//*[contains(@class,'inner-article')]//h1//a");
HtmlNodeCollection collection2 = doc.DocumentNode.SelectNodes("//*[contains(@class,'inner-article')]//p//a");


foreach (var node2 in collection2)
{
string coloursv = node2.InnerHtml.ToString();
strColour = coloursv;

//txtLog.Text += Environment.NewLine + (DateTime.Now.ToString("hh:mm:ss")) + str; - This code returns all colours (If code is ran outside of collection then only last colour in string is returned.

}

foreach (var node in collection)
{
string href = node.Attributes["href"].Value;
var itemname = node.InnerHtml.ToString();

if (itemname.Contains(txtKeyword.Text))
{
txtLog.Text = (DateTime.Now.ToString("hh:mm:ss")) + " - Item Found: " + href + " " + itemname + " " + strColour; //Successfully returns item name, colour and link but always gives last availible on website
}
}

1 个答案:

答案 0 :(得分:0)

这是因为您在循环中不断设置文本框的Text属性(因此每个项目将不断覆盖前一个):

foreach (var node in collection)
{
    // Omitted for brevity

    // This will continually overwrite the contents of your Text property
    txtLog.Text = ...;
}

如果要存储多个项目,则需要将结果存储在某种类型的集合对象(例如ListBox等)中,或者只需将值连接到文本框中:

foreach (var node in collection)
{
    // Omitted for brevity
    var stringToAdd = ...;
    txtLog.Text += stringToAdd + Environment.NewLine;
}

您也可以通过使用StringBuilder类来提高效率:

StringBuilder sb = new StringBuilder();
foreach (var node in collection)
{
    // Omitted for brevity
    var stringToAdd = ...;
    // Append this item to the results
    sb.AppendLine(stringToAdd);   
}

// Store the results
txtLog.Text = sb.ToString();