How can I change a tag name in AngleSharp?

风流意气都作罢 提交于 2021-02-11 08:39:31

问题


Is it possible to change the name of a tag from code? Something like this:

var tag = doc.QuerySelector("i");
tag.TagName = "em";

This won't work, because TagName is read-only.

But, what are my options for getting to the same end? Would I have to construct an entirely new tag and set the InnerHtml to the contents of the old tag, then delete and swap? Is this even possible?


回答1:


If you mean to replace the elements in html string then it can be done this way:

 private static string RefineImageElement(string htmlContent)
 {
     var parser = new HtmlParser();
     var document = parser.ParseDocument(htmlContent);

     foreach (var element in document.All)
     {
         if (element.LocalName == "img")
         {
             var newElement = document.CreateElement("v-img");
             newElement.SetAttribute("src", element.Attributes["src"] == null ? "" : 
              element.Attributes["src"].Value);
             newElement.SetAttribute("alt", "Article Image");

             element.Insert(AdjacentPosition.BeforeBegin, newElement.OuterHtml);
             element.Remove();
          }
      }
      return document.FirstElementChild.OuterHtml;
}



回答2:


To change element name, you can replace OuterHtml of initial element with combination of :

  1. new element opening tag
  2. initial element's InnerHtml
  3. new element closing tag

Here is an example :

var raw = @"<div>
    <i>foo</i>
</div>";
var parser = new AngleSharp.Parser.Html.HtmlParser();
var doc = parser.Parse(raw);
var tag = doc.QuerySelector("i");
tag.OuterHtml = $"<em>{tag.InnerHtml}</em>";
Console.WriteLine(doc.DocumentElement.OuterHtml);

Output :

<html><head></head><body><div>
    <em>foo</em>
</div></body></html>



回答3:


I was having the same question the other day. Later the only solution came to me is simply create another element and copy every attributes from the original element. Then remove the original element.



来源:https://stackoverflow.com/questions/37350553/how-can-i-change-a-tag-name-in-anglesharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!