问题
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 :
- new element opening tag
- initial element's
InnerHtml
- 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