【问题标题】:Validate: String must only contain <div> Tags验证:字符串只能包含 <div> 标签
【发布时间】:2019-05-21 04:13:00
【问题描述】:

如果字符串包含除 &lt;div&gt;&lt;/div&gt; 之外的任何其他 HTML 标记,如何验证?

需要看看,字符串是否包含DIV以外的元素。

实现这一目标的最佳方法是什么。

如果通过正则表达式获得此结果会很好,但不确定是否准备正则表达式以验证此场景。

有效字符串示例:

This is the data received from external <div>data string</div>. string <div>valid string</div>

无效字符串,因为它包含不是&lt;div&gt; 的 HTML 标记:

This is the data received from external <p>data string</p>. string <div>valid string</div>

【问题讨论】:

  • 向我们展示您的尝试、输入字符串和预期输出
  • 你是说你需要检查一个字符串是否包含&lt;div&gt; &lt;/div&gt;以外的标签?
  • 是的。只允许div,但是,是否存在其他任何东西,这是要检查的。
  • 我从不错过链接到stackoverflow.com/a/1732454/860585的机会
  • @Rotem 很好,我找不到那个帖子;老实说,我打算写一篇关于不使用正则表达式进行 html 解析的评论,但找不到那个帖子!

标签: c# validation


【解决方案1】:

您需要使用节点包管理器控制台安装HtmlAgilityPack

install-package htmlagilitypack

那么你可以这样使用它:

using System.Linq;
using HtmlAgilityPack;

    static void Main(string[] args)
    {
        var validstring =
            "This is the data received from external<div> data string</ div >. string <div>valid string</ div >";
        var invalidstring =
            "This is the data received from external <p>data string</p>. string <div>valid string</div>";

        var b1 = IsStringValid(validstring); // returns true
        var b2 = IsStringValid(invalidstring); // returns false
    }

    static bool IsStringValid(string str)
    {
        var pageDocument = new HtmlDocument(); // Create HtmlDocument
        pageDocument.LoadHtml(str); // Load the string into the Doc

        // check if the descendant nodes only have the names "div" and "#text"
        // "#text" is the name of any descendant that isn't inside a html-tag
        return !pageDocument.DocumentNode.Descendants().Any(node => node.Name != "div" && node.Name != "#text");
    }

【讨论】:

  • 我也研究过用 XmlReaders 解析它,但使用 HtmlAgilityPack 似乎是最方便的方法。
  • @dsi 如果这解决了您的问题,请随时接受答案。如果没有,请告诉我你的疑问。
猜你喜欢
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
  • 2015-01-27
  • 2014-11-05
  • 1970-01-01
相关资源
最近更新 更多