首页 > 解决方案 > 验证:字符串必须只包含

标签

问题描述

如果字符串包含任何其他 HTML-Tag 但如何验证<div></div>

需要看看,字符串是否包含其他DIV元素。

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

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

有效字符串的示例:

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

无效字符串,因为它包含的 HTML 标记不是<div>

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

标签: c#validation

解决方案


您需要使用节点包管理器控制台安装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");
    }

推荐阅读