c# - 使用 xsd 模式将 xml 数据中的黑名单字符

标签 c# regex xml xsd pattern-matching

我想这是一个基本问题,但模式似乎让我很困惑。 我想将一些字符列入黑名单,如 +、-、@、#、<、>。 如果字符在 xml 字段中,那么我想让 xml 无效。

在下面的示例中,如果字符串字段包含上述任何字符,我想将 xml 返回为无效。 如果数据是这样的“你好”。它应该是有效的。 我应该如何写我的模式。感谢您检查此事。

XML:

<DataType>System.String</DataType>
<Value>
      <String>Data@yours</String>
</Value>

在 XSD 中:

<xs:element name="Value">
<xs:complexType>
<xs:sequence>
<xs:element name="String" type="xs:string" />
</xs:sequence>
<xs:restriction base="xs:string">
<xs:pattern value="[^+-@#%&()<>?]"/>
</xs:restriction>
</xs:complexType>
</xs:element>

进一步编辑这部分:

我一直收到这些错误: 解析 EntityName 时出错。 - 在我的代码中 在唯一的 xsd 验证器工具中,实体名称必须紧跟在实体引用中的 & 之后。 http://www.utilities-online.info/xsdvalidation/#.VzTwcYSDFBc

好像跟不上这些特殊字符,请问怎么改? 再次感谢。

最佳答案

请注意,acc。至 regular-expressions.info :

Particularly noteworthy is the complete absence of anchors like the caret and dollar, word boundaries, and lookaround. XML schema always implicitly anchors the entire regular expression. The regex must match the whole element for the element to be considered valid.

所以,要匹配一个不包含+的字符串, @ , # , % , & , ( , ) , < , > , ? , - (至少1个符号),你需要使用

<xs:pattern value="[^+@#%&amp;()&lt;&gt;?-]+"/>

请注意 < , >&应该被实体化以在 XML 属性值中使用。

如果你想允许空值,*应该使用而不是 + .注意 -放在模式的末尾,以免创建这样的范围:

enter image description here

关于c# - 使用 xsd 模式将 xml 数据中的黑名单字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37196337/

相关文章:

mysql - 转义mySQL正则表达式中的问号

c# - 如果元素中存在属性,则将 XAttribute 添加到 XElement

c++ - XML文件生成器

c# - 来自其他 dll 的 PropertyInfo GetCustomAtributes

c# - 使用 LINQ 查找最常用的单词

正则表达式允许带有前导特殊字符的数字

Javascript trim 多行字符串而不切割单词

c# - 生成 C# 对象代码并从 xml 文档为其属性赋值

c# - 将文件扩展名与程序相关联的最佳方法

c# - 快速创建 Pdf 的库