【问题标题】:Html Agility Pack/C#: how to create/replace tags?Html Agility Pack/C#:如何创建/替换标签?
【发布时间】:2011-09-26 06:39:53
【问题描述】:

任务很简单,但我找不到答案。

使用 Node.Remove() 可以轻松删除标签(节点)...但是如何替换它们呢?

有一个 ReplaceChild() 方法,但它需要创建一个新标签。如何设置标签的内容? InnerHtml 和 OuterHtml 是只读属性。

【问题讨论】:

    标签: c# html parsing


    【解决方案1】:

    您确定 InnerHtml 是只读属性吗?

    HTMLAgility 包的文档另有说明:(剪切和粘贴)

    Gets or Sets the HTML between the start and end tags of the object.
    
    Namespace:  HtmlAgilityPack
    Assembly:  HtmlAgilityPack (in HtmlAgilityPack.dll) Version: 1.4.0.0 (1.4.0.0)
    Syntax
    C# 
    public virtual string InnerHtml { get; set; }
    

    如果它是只读的,您可以发布一些代码吗?

    【讨论】:

      【解决方案2】:

      查看这段代码sn-p:

      public string ReplaceTextBoxByLabel(string htmlContent) 
      {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(htmlContent);
      
        foreach(HtmlNode tb in doc.DocumentNode.SelectNodes("//input[@type='text']"))
        {
          string value = tb.Attributes.Contains("value") ? tb.Attributes["value"].Value : " ";
          HtmlNode lbl = doc.CreateElement("span");
          lbl.InnerHtml = value;
      
          tb.ParentNode.ReplaceChild(lbl, tb);
        }
      
        return doc.DocumentNode.OuterHtml;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-24
        • 1970-01-01
        • 1970-01-01
        • 2017-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多