【问题标题】:Using Htmlagility pack getting attribute values使用 Htmlagility 包获取属性值
【发布时间】:2013-07-27 06:28:37
【问题描述】:

使用Htmlagilitypack我可以通过以下代码获取一个标签的属性值:

public string parseinput(HtmlDocument HtmlDocument)
{
     try
     {
            return HtmlDocument.DocumentNode.SelectSingleNode("//input[@type=""text""]").Attributes["value"].Value;
     }

     catch (Exception ex)
     {
          string x= ex.ToString();
            return "Error is... '"+x+"'" ;
     }
 }

当它获得第一个值时,它会停止执行并给出该值,但我需要将所有这些文本类型值作为输出。

为此我需要做什么?

【问题讨论】:

  • 你想要的输出格式是什么?
  • 它应该返回文本类型的名称和值。以输入标签类型为“隐藏”为例。所以它应该返回所有那些隐藏类型的标签的名称和值......

标签: c# html-parsing html-agility-pack


【解决方案1】:

你需要SelectNodes 而不是SelectSingleNode

return String.Join(",", HtmlDocument.DocumentNode.SelectNodes("//input[@type=""text""]")
                         .Select(n=>n.Attributes["value"].Value)

如果你需要输入类型和值

var inputs = doc.DocumentNode.SelectNodes("//input").Select(n => new { 
                 Type = n.Attributes["type"].Value, Value = n.Attributes["value"].Value }).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-03
    • 2016-06-30
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多