[英]Validate: String must only contain <div> Tags
如何验证字符串是否包含除<div></div>
任何其他HTML-Tag?
需要看到,字符串是否包含其他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>
您需要使用节点程序包管理器控制台安装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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.