【发布时间】:2014-08-07 01:22:34
【问题描述】:
我再次迷失了 HTMLAgility。
这是我正在使用的 HTML 字符串:
<table>...</table>
我正在尝试通过添加以下内容来纠正此问题:
<html>
<head>
...
</head>
<body>
<table>
...
</table>
</body>
</html>
这是我的代码,我可以获取除正文之外的所有内容。 有什么建议吗?
HtmlNode htmlNode = doc.DocumentNode.SelectSingleNode("//html");
if (htmlNode == null)
{
htmlNode = doc.CreateElement("html");
HtmlNodeCollection htmlCollection = doc.DocumentNode.ChildNodes;
htmlNode.AppendChildren(htmlCollection);
doc.DocumentNode.RemoveAllChildren();
doc.DocumentNode.PrependChild(htmlNode);
}
//check if <head> exists, if not create <head>
HtmlNode head = doc.DocumentNode.SelectSingleNode("//head");
if (head == null)
{
head = doc.CreateElement("head");
HtmlNodeCollection htmlCollection = doc.DocumentNode.ChildNodes;
htmlNode.PrependChild(head);
}
HtmlNode cssLink = doc.DocumentNode.SelectSingleNode("//link[contains(@href, " + Url.Content("/assets/global/css/reset.css") + ")]");
if (cssLink == null)
{
cssLink = doc.CreateElement("link");
cssLink.SetAttributeValue("rel", "stylesheet");
cssLink.SetAttributeValue("href", Url.Content("/assets/global/css/reset.css"));
head.AppendChild(cssLink);
}
//check if <body> exists, if yes, add style='margin:0; padding:0'
HtmlNode htmlBody = doc.DocumentNode.SelectSingleNode("//body");
if (htmlBody == null)
{
head = doc.DocumentNode.SelectSingleNode("//head");
htmlBody = htmlNode.CloneNode("body", true);
htmlNode.ChildNodes.Clear();
htmlNode.AppendChild(htmlBody);
//HtmlNodeCollection htmlCollection = doc.DocumentNode.ChildNodes;
//htmlBody.AppendChildren(htmlCollection);
//doc.DocumentNode.RemoveAllChildren();
//doc.InsertBefore(htmlBody);
//head.DocumentNode.AppendChild(htmlBody);
//htmlNode.PrependChild(htmlBody);
}
这段代码给了我这个——你可以看到<body> 放错了地方。
<html>
<body>
<head>
...
</head>
<table>
...
</table>
</body>
</html>
【问题讨论】:
标签: c# asp.net-mvc-4 html-agility-pack nodes