HTML敏捷性包/ C#:如何创建/替换标签? [英] Html Agility Pack/C#: how to create/replace tags?

查看:192
本文介绍了HTML敏捷性包/ C#:如何创建/替换标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The task is simple, but I couldn't find the answer.

删除标记(节点)很容易与Node.Remove()...但如何他们更换?

Removing tags (nodes) is easy with Node.Remove()... But how to replace them?

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

There's a ReplaceChild() method, but it requires to create a new tag. How do I set the contents of a tag? InnerHtml and OuterHtml are read only properties.

推荐答案

请参阅此代码段:

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;
}

这篇关于HTML敏捷性包/ C#:如何创建/替换标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆