使用HTMLAgilityPack以特定順序插入節點時遇到問題

asp.net-mvc-4 c# html-agility-pack nodes

我再次迷失了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>

一般承認的答案

您可以嘗試在添加<head>之前先添加<body>節點,因為您似乎希望除<head>之外的<html>所有內容都放在<body>標記內:

.....
HtmlNode htmlBody = doc.DocumentNode.SelectSingleNode("//body");
if (htmlBody == null)
{
    htmlBody = doc.CreateElement("body");
    //move all child of <html> to be child of <body>
    HtmlNodeCollection htmlCollection = htmlNode.ChildNodes;
    htmlBody.AppendChildren(htmlCollection);
    htmlNode.RemoveAllChildren();
    //add <body> to <html>
    htmlNode.PrependChild(htmlBody);
}

//check if <head> exists, if not create <head>
HtmlNode head = doc.DocumentNode.SelectSingleNode("//head");
if (head == null)
{
    //add <head> to <html>
    head = doc.CreateElement("head");
    htmlNode.PrependChild(head);
}
.....


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow