繁体   English   中英

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

[英]C# - Public string only stores last value outside of collection

我正在使用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
}
}

这是因为您正在循环中不断设置Text框的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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM