XML模式验证无法验证从正则字符串示例生成器获取的输入

本文关键字:验证 获取 输入 字符串 模式 XML | 更新日期: 2023-09-27 18:05:09

我无法通过特定元素的xsd验证。

在展示我的代码之前,请注意我已经被第三方接收到的xsd,并且我被迫坚持工作,不做任何更改。

问题:对于给定元素,xsd regex验证模式失败,并显示消息

The value '...' is invalid according to its datatype 'String' - The Pattern constraint failed.

现在,模式是非常长和复杂的,我一直避免尝试理解它,并求助于正则表达式示例字符串生成器。

作为这样的例子,我确实使用了以下内容:

1

。http://uttool.com/text/regexstr/default.aspx

2

。https://github.com/moodmosaic/Fare (c#)

在使用上面提到的工具验证自动生成的示例时,我使用http://www.regexr.com/。

我没有找到一个自动生成的样本,regexr.com没有确认它是匹配的。

然而,我的模式验证失败。

我创建了一个代码示例来说明这个问题:

Xsd :

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema version="1.0" elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="MyField">
    <xsd:annotation>
      <xsd:documentation>
        MyField Display Text
      </xsd:documentation>
    </xsd:annotation>
    <xsd:simpleType>
      <xsd:restriction base="xsd:string">
        <xsd:pattern value="([0-9]'d{3}((0[1-9]|1[012])(0[1-9]|1'd|2[0-8])|(0[13456789]|1[012])(29|30)|(0[13578]|1[02])31)|(15(8[48]|9[26])|(1[6-9]|[2-9]'d)(0[48]|[13579][26]|[2468][048])|([2468][048]|16|3579[26])00)0229)((0[0-9]|1[0-9]|2[0-3])([0-5]'d){2})" />
      </xsd:restriction>
    </xsd:simpleType>
  </xsd:element>
</xsd:schema>

Xml>:
<?xml version="1.0" encoding="utf-8" ?>
<MyField>
  62710522201745
</MyField>

验证代码:

string xsdTestMarkup = File.ReadAllText(GetPath("TestSchema.xsd"));
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdTestMarkup)));
DirectoryInfo filesFolder = new DirectoryInfo("...myPath...");
FileInfo[] files = filesFolder.GetFiles("*.xml", SearchOption.TopDirectoryOnly);
List<XDocument> xmlDocs = new List<XDocument>();
foreach (FileInfo file in files)
{
    xmlDocs.Add(XDocument.Load(file.FullName));
}
for(int i = 0; i < xmlDocs.Count; i++)
{
    Console.WriteLine("Validating file [{0}]...", files[i].Name);
    List<string> errors = new List<string>();
    xmlDocs[i].Validate(schemas, (o, e) =>
    {
        errors.Add(e.Message);
    });
    File.WriteAllLines(GetPath("ValidationErrors" )+ Path.GetFileNameWithoutExtension(files[i].Name) + ".txt", errors);
}

怎么了?是验证本身吗?我在这个xsd中使用了其他几个使用"pattern"的验证(使用不同的模式),它们都没有问题地通过了。

XML模式验证无法验证从正则字符串示例生成器获取的输入

不加空格试试。似乎可以正常工作。

还要注意XSD中使用的正则表达式规则与标准正则表达式规则略有不同,我认为在这种情况下没有任何区别,但值得了解。

<?xml version="1.0" encoding="utf-8" ?>
<!-- Created with Liquid XML 2015 Designer Edition (Trial) 13.1.0.5909 (http://www.liquid-technologies.com) -->
<MyField>62710522201745</MyField>