Reputation: 3580
I'm trying to create a XHTMl file from scratch using HtmlAgilityPack. Following the advice presented in Add a doctype to HTML via HTML Agility pack, I try to add a doctype to it:
private static HtmlDocument createEmptyDoc()
{
HtmlDocument titlePage = new HtmlDocument();
titlePage.OptionOutputAsXml = true;
titlePage.OptionCheckSyntax = true;
titlePage.AddDoctype();
var html = titlePage.CreateElement("html");
titlePage.DocumentNode.AppendChild(html);
return titlePage;
}
public static class HtmlDocumentExtensions
{
public static void AddDoctype(this HtmlDocument doc)
{
var doctype = doc.DocumentNode.PrependChild(doc.CreateComment("<!doctype html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">"));
}
}
However, when I write this document to a file, it looks like this:
<?xml version="1.0" encoding="iso-8859-1"?>
<!--type html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.d-->
<html />
The doctype really gets treated as a comment and some characters are replaced by dashes. How can I solve this and write the doctype as-is to the file?
EDIT: Added custom extension to HtmlDocument
Upvotes: 3
Views: 725
Reputation: 801
Try this:
using HtmlAgilityPack;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
HtmlDocument doc = new HtmlDocument();
HtmlNode docNode = HtmlNode.CreateNode("<html><head></head><body></body></html>");
HtmlNode rootNode = HtmlNode.CreateNode("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
doc.DocumentNode.AppendChild(rootNode);
doc.DocumentNode.AppendChild(docNode);
doc.Save("test.html");
}
}
}
Upvotes: 1
Reputation: 18127
static void Main(string[] args)
{
string html = @"
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<table>
<tr>
<td>A!!</td>
<td>te2</td>
<td>2!!</td>
<td>te43</td>
<td></td>
<td> !!</td>
<td>.!!</td>
<td>te53</td>
<td>te2</td>
<td>texx</td>
</tr>
</table>
<h4 class=""nikstyle_title""><a rel=""nofollow"" target=""_blank"" href=""http://www.niksalehi.com/ccount/click.php?ref=ZDNkM0xuQmxjbk5wWVc1MkxtTnZiUT09&id=117""><span class=""text-matn-title-bold-black"">my text</span></a></h4>
</body>
</html>";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
var doctype = doc.DocumentNode.SelectSingleNode("/comment()[starts-with(.,'<!DOCTYPE')]");
if (doctype == null)
doctype = doc.DocumentNode.PrependChild(doc.CreateComment());
doctype.InnerHtml = "<!DOCTYPE html>";
string html2 = doc.DocumentNode.InnerHtml;
}
The code in other question gives you the way to do it. Here is full example.
Upvotes: 1