c# - 验证:字符串必须只包含标签
问题描述
如果字符串包含任何其他 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>
解决方案
您需要使用节点包管理器控制台安装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");
}
推荐阅读
- ios - 在 UITextView 顶部插入(附加)文本 - Swift
- scala - 当我编写 zipInputStream 时在 S3 中获取 0KB 文件
- r - 检查 write_xlsx 是否已正确执行并且文件是否已写入
- amazon-ec2 - 将 scylla 集群切换到大型 aws 实例的简单方法
- sql - 为什么没有在 SQL Server 2008 (Visual Studio 2010) 中创建用户实例?
- python - 是否可以将两个预先存在的数据库合并到一个前端?
- c# - C#异步LCD写
- angular - Angular github 页面路径具有重复的应用程序名称
- django - 如何在保存模型方法 DJANGO 中获取绝对 url?
- angular - Prime NG 的可编辑表上的奇怪行为