<i id='Ph09b'><tr id='Ph09b'><dt id='Ph09b'><q id='Ph09b'><span id='Ph09b'><b id='Ph09b'><form id='Ph09b'><ins id='Ph09b'></ins><ul id='Ph09b'></ul><sub id='Ph09b'></sub></form><legend id='Ph09b'></legend><bdo id='Ph09b'><pre id='Ph09b'><center id='Ph09b'></center></pre></bdo></b><th id='Ph09b'></th></span></q></dt></tr></i><div id='Ph09b'><tfoot id='Ph09b'></tfoot><dl id='Ph09b'><fieldset id='Ph09b'></fieldset></dl></div>

        <legend id='Ph09b'><style id='Ph09b'><dir id='Ph09b'><q id='Ph09b'></q></dir></style></legend>

      1. <tfoot id='Ph09b'></tfoot>

          <bdo id='Ph09b'></bdo><ul id='Ph09b'></ul>

        <small id='Ph09b'></small><noframes id='Ph09b'>

        HTML Agility Pack 条带标签不在白名单中

        时间:2023-11-10
          <tbody id='w2D3n'></tbody>

              <i id='w2D3n'><tr id='w2D3n'><dt id='w2D3n'><q id='w2D3n'><span id='w2D3n'><b id='w2D3n'><form id='w2D3n'><ins id='w2D3n'></ins><ul id='w2D3n'></ul><sub id='w2D3n'></sub></form><legend id='w2D3n'></legend><bdo id='w2D3n'><pre id='w2D3n'><center id='w2D3n'></center></pre></bdo></b><th id='w2D3n'></th></span></q></dt></tr></i><div id='w2D3n'><tfoot id='w2D3n'></tfoot><dl id='w2D3n'><fieldset id='w2D3n'></fieldset></dl></div>

                <tfoot id='w2D3n'></tfoot>

                <small id='w2D3n'></small><noframes id='w2D3n'>

                <legend id='w2D3n'><style id='w2D3n'><dir id='w2D3n'><q id='w2D3n'></q></dir></style></legend>
                  <bdo id='w2D3n'></bdo><ul id='w2D3n'></ul>

                • 本文介绍了HTML Agility Pack 条带标签不在白名单中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我正在尝试创建一个函数来删除不在白名单中的 html 标记和属性.我有以下 HTML:

                  I'm trying to create a function which removes html tags and attributes which are not in a white list. I have the following HTML:

                  <b>first text </b>
                  <b>second text here
                         <a>some text here</a>
                   <a>some text here</a>
                  
                   </b>
                  <a>some twxt here</a>
                  

                  我正在使用 HTML 敏捷包,目前我的代码是:

                  I am using HTML agility pack and the code I have so far is:

                  static List<string> WhiteNodeList = new List<string> { "b" };
                  static List<string> WhiteAttrList = new List<string> { };
                  static HtmlNode htmlNode;
                  public static void RemoveNotInWhiteList(out string _output, HtmlNode pNode, List<string> pWhiteList, List<string> attrWhiteList)
                  {
                  
                   // remove all attributes not on white list
                   foreach (var item in pNode.ChildNodes)
                   {
                    item.Attributes.Where(u => attrWhiteList.Contains(u.Name) == false).ToList().ForEach(u => RemoveAttribute(u));
                  
                   }
                  
                   // remove all html and their innerText and attributes if not on whitelist.
                   //pNode.ChildNodes.Where(u => pWhiteList.Contains(u.Name) == false).ToList().ForEach(u => u.Remove());
                   //pNode.ChildNodes.Where(u => pWhiteList.Contains(u.Name) == false).ToList().ForEach(u => u.ParentNode.ReplaceChild(ConvertHtmlToNode(u.InnerHtml),u));
                   //pNode.ChildNodes.Where(u => pWhiteList.Contains(u.Name) == false).ToList().ForEach(u => u.Remove());
                  
                   for (int i = 0; i < pNode.ChildNodes.Count; i++)
                   {
                    if (!pWhiteList.Contains(pNode.ChildNodes[i].Name))
                    {
                     HtmlNode _newNode = ConvertHtmlToNode(pNode.ChildNodes[i].InnerHtml);
                     pNode.ChildNodes[i].ParentNode.ReplaceChild(_newNode, pNode.ChildNodes[i]);
                     if (pNode.ChildNodes[i].HasChildNodes && !string.IsNullOrEmpty(pNode.ChildNodes[i].InnerText.Trim().Replace("
                  ", "")))
                     {
                      HtmlNode outputNode1 = pNode.ChildNodes[i];
                      for (int j = 0; j < pNode.ChildNodes[i].ChildNodes.Count; j++)
                      {
                       string _childNodeOutput;
                       RemoveNotInWhiteList(out _childNodeOutput,
                            pNode.ChildNodes[i], WhiteNodeList, WhiteAttrList);
                       pNode.ChildNodes[i].ReplaceChild(ConvertHtmlToNode(_childNodeOutput), pNode.ChildNodes[i].ChildNodes[j]);
                       i++;
                      }
                     }
                    }
                   }
                  
                   // Console.WriteLine(pNode.OuterHtml);
                   _output = pNode.OuterHtml;
                  }  
                  
                  private static void RemoveAttribute(HtmlAttribute u)
                  {
                   u.Value = u.Value.ToLower().Replace("javascript", "");
                   u.Remove();
                  
                  }
                  
                  public static HtmlNode ConvertHtmlToNode(string html)
                  {
                   HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                   doc.LoadHtml(html);
                   if (doc.DocumentNode.ChildNodes.Count == 1)
                    return doc.DocumentNode.ChildNodes[0];
                   else return doc.DocumentNode;
                  }
                  

                  我想达到的输出是

                  <b>first text </b>
                  <b>second text here
                         some text here
                   some text here
                  
                   </b>
                  some twxt here
                  

                  这意味着我只想保留 <b> 标签.
                  我这样做的原因是因为一些用户将 MS WORD 中的 cpoy-paste 粘贴到 ny WYSYWYG html 编辑器中.

                  That means that I only want to keep the <b> tags.
                  The reason i'm doing this is because Some of the users do cpoy-paste from MS WORD into ny WYSYWYG html editor.

                  谢谢!

                  推荐答案

                  嘿,显然我几乎在某人的博客文章中找到了答案....

                  heh, apparently I ALMOST found an answer in a blog post someone made....

                  using System.Collections.Generic;
                  using System.Linq;
                  using HtmlAgilityPack;
                  
                  namespace Wayloop.Blog.Core.Markup
                  {
                      public static class HtmlSanitizer
                      {
                          private static readonly IDictionary<string, string[]> Whitelist;
                  
                          static HtmlSanitizer()
                          {
                              Whitelist = new Dictionary<string, string[]> {
                                  { "a", new[] { "href" } },
                                  { "strong", null },
                                  { "em", null },
                                  { "blockquote", null },
                                  };
                          }
                  
                          public static string Sanitize(string input)
                          {
                              var htmlDocument = new HtmlDocument();
                  
                              htmlDocument.LoadHtml(input);
                              SanitizeNode(htmlDocument.DocumentNode);
                  
                              return htmlDocument.DocumentNode.WriteTo().Trim();
                          }
                  
                          private static void SanitizeChildren(HtmlNode parentNode)
                          {
                              for (int i = parentNode.ChildNodes.Count - 1; i >= 0; i--) {
                                  SanitizeNode(parentNode.ChildNodes[i]);
                              }
                          }
                  
                          private static void SanitizeNode(HtmlNode node)
                          {
                              if (node.NodeType == HtmlNodeType.Element) {
                                  if (!Whitelist.ContainsKey(node.Name)) {
                                      node.ParentNode.RemoveChild(node);
                                      return;
                                  }
                  
                                  if (node.HasAttributes) {
                                      for (int i = node.Attributes.Count - 1; i >= 0; i--) {
                                          HtmlAttribute currentAttribute = node.Attributes[i];
                                          string[] allowedAttributes = Whitelist[node.Name];
                                          if (!allowedAttributes.Contains(currentAttribute.Name)) {
                                              node.Attributes.Remove(currentAttribute);
                                          }
                                      }
                                  }
                              }
                  
                              if (node.HasChildNodes) {
                                  SanitizeChildren(node);
                              }
                          }
                      }
                  }
                  

                  我从这里得到了 HtmlSanitizer显然它并没有去除标签,而是完全删除了元素.

                  I got HtmlSanitizer from here Apparently it does not strip th tags, but removes the element altoghether.

                  好的,这是以后需要的人的解决方案.

                  OK, here is the solution for those who will need it later.

                  public static class HtmlSanitizer
                      {
                          private static readonly IDictionary<string, string[]> Whitelist;
                          private static List<string> DeletableNodesXpath = new List<string>();
                  
                          static HtmlSanitizer()
                          {
                              Whitelist = new Dictionary<string, string[]> {
                                  { "a", new[] { "href" } },
                                  { "strong", null },
                                  { "em", null },
                                  { "blockquote", null },
                                  { "b", null},
                                  { "p", null},
                                  { "ul", null},
                                  { "ol", null},
                                  { "li", null},
                                  { "div", new[] { "align" } },
                                  { "strike", null},
                                  { "u", null},                
                                  { "sub", null},
                                  { "sup", null},
                                  { "table", null },
                                  { "tr", null },
                                  { "td", null },
                                  { "th", null }
                                  };
                          }
                  
                          public static string Sanitize(string input)
                          {
                              if (input.Trim().Length < 1)
                                  return string.Empty;
                              var htmlDocument = new HtmlDocument();
                  
                              htmlDocument.LoadHtml(input);            
                              SanitizeNode(htmlDocument.DocumentNode);
                              string xPath = HtmlSanitizer.CreateXPath();
                  
                              return StripHtml(htmlDocument.DocumentNode.WriteTo().Trim(), xPath);
                          }
                  
                          private static void SanitizeChildren(HtmlNode parentNode)
                          {
                              for (int i = parentNode.ChildNodes.Count - 1; i >= 0; i--)
                              {
                                  SanitizeNode(parentNode.ChildNodes[i]);
                              }
                          }
                  
                          private static void SanitizeNode(HtmlNode node)
                          {
                              if (node.NodeType == HtmlNodeType.Element)
                              {
                                  if (!Whitelist.ContainsKey(node.Name))
                                  {
                                      if (!DeletableNodesXpath.Contains(node.Name))
                                      {                       
                                          //DeletableNodesXpath.Add(node.Name.Replace("?",""));
                                          node.Name = "removeableNode";
                                          DeletableNodesXpath.Add(node.Name);
                                      }
                                      if (node.HasChildNodes)
                                      {
                                          SanitizeChildren(node);
                                      }                  
                  
                                      return;
                                  }
                  
                                  if (node.HasAttributes)
                                  {
                                      for (int i = node.Attributes.Count - 1; i >= 0; i--)
                                      {
                                          HtmlAttribute currentAttribute = node.Attributes[i];
                                          string[] allowedAttributes = Whitelist[node.Name];
                                          if (allowedAttributes != null)
                                          {
                                              if (!allowedAttributes.Contains(currentAttribute.Name))
                                              {
                                                  node.Attributes.Remove(currentAttribute);
                                              }
                                          }
                                          else
                                          {
                                              node.Attributes.Remove(currentAttribute);
                                          }
                                      }
                                  }
                              }
                  
                              if (node.HasChildNodes)
                              {
                                  SanitizeChildren(node);
                              }
                          }
                  
                          private static string StripHtml(string html, string xPath)
                          {
                              HtmlDocument htmlDoc = new HtmlDocument();
                              htmlDoc.LoadHtml(html);
                              if (xPath.Length > 0)
                              {
                                  HtmlNodeCollection invalidNodes = htmlDoc.DocumentNode.SelectNodes(@xPath);
                                  foreach (HtmlNode node in invalidNodes)
                                  {
                                      node.ParentNode.RemoveChild(node, true);
                                  }
                              }
                              return htmlDoc.DocumentNode.WriteContentTo(); ;
                          }
                  
                          private static string CreateXPath()
                          {
                              string _xPath = string.Empty;
                              for (int i = 0; i < DeletableNodesXpath.Count; i++)
                              {
                                  if (i != DeletableNodesXpath.Count - 1)
                                  {
                                      _xPath += string.Format("//{0}|", DeletableNodesXpath[i].ToString());
                                  }
                                  else _xPath += string.Format("//{0}", DeletableNodesXpath[i].ToString());
                              }
                              return _xPath;
                          }
                      }
                  

                  我重命名了节点,因为如果我必须解析 XML 命名空间节点,它会在 xpath 解析时崩溃.

                  I renamed the node because if I had to parse an XML namespace node it would crash on the xpath parsing.

                  这篇关于HTML Agility Pack 条带标签不在白名单中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  上一篇:Jenkins REST API 获取作业和作业控制台日志 下一篇:如何在服务器控件属性中使用 ASP.NET &lt;%= 标签?

                  相关文章

                    <bdo id='LUDwC'></bdo><ul id='LUDwC'></ul>

                  <small id='LUDwC'></small><noframes id='LUDwC'>

                    <i id='LUDwC'><tr id='LUDwC'><dt id='LUDwC'><q id='LUDwC'><span id='LUDwC'><b id='LUDwC'><form id='LUDwC'><ins id='LUDwC'></ins><ul id='LUDwC'></ul><sub id='LUDwC'></sub></form><legend id='LUDwC'></legend><bdo id='LUDwC'><pre id='LUDwC'><center id='LUDwC'></center></pre></bdo></b><th id='LUDwC'></th></span></q></dt></tr></i><div id='LUDwC'><tfoot id='LUDwC'></tfoot><dl id='LUDwC'><fieldset id='LUDwC'></fieldset></dl></div>
                  1. <legend id='LUDwC'><style id='LUDwC'><dir id='LUDwC'><q id='LUDwC'></q></dir></style></legend>
                      <tfoot id='LUDwC'></tfoot>