如何通过 XmlReader ValidationType.Schema 检测违反 xsd:unique 约束的情况

问题描述 投票:0回答:1

以下演示代码验证 XML 是否与给定的 XSD 匹配。 但它不会检测 XML 是否违反任何 xsd:unique 约束。这是为什么,更重要的是,我如何验证唯一约束?

using var schemaReader = XmlReader.Create(pathToXsd);

var validationErrors = new StringBuilder();

var readerSettings = new XmlReaderSettings();
readerSettings.Schemas.Add(targetNamespace, schemaReader);
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.ValidationEventHandler += (s, e) => validationErrors.AppendLine($"{e.Severity} {e.Message}");
using var reader = XmlReader.Create(pathToXml, readerSettings);

while (reader.Read())
{
    // Read the whole xml file just for invoking validation.
}

if (validationErrors.Length == 0)
   throw new Exception("given XML should violate us:unique constraint");

演示 XSD(借自 如何使属性在 xml 模式中唯一?

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema xmlns="http://Test.xsd"
  targetNamespace="http://Test.xsd"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  elementFormDefault="qualified">
  <xsd:element name="books">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="book" maxOccurs="unbounded">
          <xsd:complexType>
            <xsd:attribute name="isbn" type="xsd:string" />
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
    <xsd:unique name="unique-isbn">
      <xsd:selector xpath="book" />
      <xsd:field xpath="@isbn" />
    </xsd:unique>
  </xsd:element>
</xsd:schema>

演示 XML

    <books xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://Test.xsd">
    <book isbn="abc"/>
    <book isbn="def"/>
    <book isbn="def"/><!-- this line should raise an error -->
</books>
c# xml xsd-validation
1个回答
0
投票

确保将验证标志设置为

ProcessIdentityConstraints
https://learn.microsoft.com/en-us/dotnet/api/system.xml.schema.xmlschemavalidationflags?view=net-8.0.

另请参阅有关命名空间问题的评论。

© www.soinside.com 2019 - 2024. All rights reserved.