首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有IF语句的C# HTML敏捷包

问带有IF语句的C# HTML敏捷包
EN

Stack Overflow用户
提问于 2011-11-15 02:16:33
回答 1查看 833关注 0票数 0

我有这段代码,我需要运行if语句来设置变量的值。问题是,当第一个条件为空时,它就失败了。有人能告诉我我哪里做错了吗?

IF语句位于foreach循环中,该循环在每次迭代时向列表中添加一个值。

非常感谢!

代码语言:javascript
复制
 string result = string.Empty;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";

        using (var stream = request.GetResponse().GetResponseStream())
        using (var reader = new StreamReader(stream, Encoding.UTF8))
        {
            result = reader.ReadToEnd();
        }

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(new StringReader(result));
        HtmlNode root = doc.DocumentNode;

        string itemdesc = doc.DocumentNode.SelectSingleNode("//h1[@class='producttitle']").InnerText;

        HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='resultsset']/table/tbody[@class='result']/tr");

        List<string> sellers = new List<string>();
        List<string> prices = new List<string>();

        foreach (HtmlNode node in nodes)
        {
            string seller = string.Empty;
                if(node.SelectSingleNode(".//ul[@class='sellerInformation']/img").GetAttributeValue("alt", string.Empty) != null)
                {
                    seller = node.SelectSingleNode(".//ul[@class='sellerInformation']/img").GetAttributeValue("alt", string.Empty);
                }

                else if (node.SelectSingleNode(".//ul[@class='sellerInformation']/a/img").GetAttributeValue("alt", string.Empty) != null)
                {
                    seller = node.SelectSingleNode(".//ul[@class='sellerInformation']/a/img").GetAttributeValue("alt", string.Empty);
                }

                else
                {
                    seller = node.SelectSingleNode(".//ul[@class='sellerInformation']/li/div/span/a/b").InnerText;
                }


            sellers.Add(seller);
            string price = node.SelectSingleNode(".//span[@class='price']").InnerText;
            prices.Add(price);

        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-15 02:19:01

可能SelectSingleNode返回的是null,因此对GetAttributeValue的调用是一个null引用问题。在检查属性之前,您需要检查SelectSingleNode的结果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8126141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档