gpt4 book ai didi

c# - HTML敏捷包: how to create indented HTML?

转载 作者:太空狗 更新时间:2023-10-29 18:19:12 24 4
gpt4 key购买 nike

所以,我正在使用 HtmlAgilityPack 生成 html,它运行良好,但 html 文本没有缩进。然而,我可以获得缩进的 XML,但我需要 HTML。有办法吗?

HtmlDocument doc = new HtmlDocument();

// gen html
HtmlNode table = doc.CreateElement("table");
table.Attributes.Add("class", "tableClass");
HtmlNode tr = doc.CreateElement("tr");
table.ChildNodes.Append(tr);
HtmlNode td = doc.CreateElement("td");
td.InnerHtml = "—";
tr.ChildNodes.Append(td);

// write text, no indent :(
using(StreamWriter sw = new StreamWriter("table.html"))
{
table.WriteTo(sw);
}

// write xml, nicely indented but it's XML!
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlWriter xw = XmlTextWriter.Create("table.xml", settings))
{
table.WriteTo(xw);
}

最佳答案

快速、可靠、纯 C#、.NET Core 兼容的 AngleSharp

你可以用 AngleSharp 解析它它提供了一种自动缩进的方法:

var parser = new HtmlParser();
var document = parser.ParseDocument(text);
using (var writer = new StringWriter())
{
document.ToHtml(writer, new PrettyMarkupFormatter
{
Indentation = "\t",
NewLine = "\n"
});
var indentedText = writer.ToString();
}

关于c# - HTML敏捷包: how to create indented HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5937185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com