c# - 使用 .NET 4.6 验证 xml 时出现 NullReferenceException

标签 c# .net xsd

我正在测试从 .NET 版本 4.5.1 到 4.6 的切换,并在对可选属性使用唯一约束时在 xsd 验证中遇到 NullReferenceException。

at System.Xml.Schema.KeySequence.ToString()
at System.Xml.Schema.XmlSchemaValidator.EndElementIdentityConstraints(Object typedValue, String stringValue, XmlSchemaDatatype datatype)
at System.Xml.Schema.XmlSchemaValidator.InternalValidateEndElement(XmlSchemaInfo schemaInfo, Object typedValue)
at System.Xml.XsdValidatingReader.ProcessEndElementEvent()
at System.Xml.XsdValidatingReader.ProcessElementEvent()
at System.Xml.XsdValidatingReader.ProcessReaderEvent()
at System.Xml.XsdValidatingReader.Read()
at ConsoleApplication.Program.Main(String[] args)

这是被剥离的代码,在以 v4.5.x 为目标时运行,但在使用 4.6 时失败并出现 NullReferenceException。 (在Win7上用VS2013和VS2015测试)。这在 xml 中合法吗?即使不是,它也应该引发一些 XmlException。

架构:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Enumerations">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Enum" minOccurs="0" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="id" type="xs:string" use="optional"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
    <xs:unique name="unique_EnumId_contraint">
      <xs:selector xpath="Enum"/>
      <xs:field xpath="@id"/>
    </xs:unique>
  </xs:element>
</xs:schema>

XML:

<?xml version="1.0" encoding="utf-8"?>
<Enumerations>
  <Enum />
  <Enum />
</Enumerations>

C# 代码:

var settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, "enumerations.xsd");

using (var xmlReader = XmlReader.Create("enumerations.xml", settings))
{
    while (xmlReader.Read())
    {
        if (xmlReader.NodeType == XmlNodeType.Element)
        {
            Console.CursorLeft = xmlReader.Depth * 4;
            Console.WriteLine(xmlReader.Name);
        }
    }
}

最佳答案

我可以重现这个。对我来说看起来像一个错误( <rant> .NET 4.6 有很多... </rant> )。您应该将其报告给Microsoft Connect .

虽然此问题已修复,但您可以在此处查看来源:http://referencesource.microsoft.com/#System.Xml/System/Xml/Schema/ConstraintStruct.cs,091791a9542f1952

它告诉我们可以使用 AppContext 来克服它开关,因此只需在任何其他代码之前添加此代码即可工作:

AppContext.SetSwitch("Switch.System.Xml.IgnoreEmptyKeySequences", true);

有关此开关的更多信息可在此处找到:Mitigation: XML Schema Validation - 请注意这句话:“此更改的影响应该很小”:-)

PS:我相信您也可以使用正确的 .config 文件更改这些开关。

关于c# - 使用 .NET 4.6 验证 xml 时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32786073/

相关文章:

jaxb - XSD 允许扩展、兼容性和验证

java - 如何使用 JAXB 在我的 Java 代码中创建 UUID 以传递 XSD 模式限制

c# - 客户端消息功能

.net - 在游戏开发和 VirtualBox 等应用程序方面,C++ 比 .NET 有什么优势

c# - 通过代码,我怎样才能让硬盘驱动器进入休眠状态

c# - 强制开发人员使用特定的构造函数

.net - 如何在winforms的设计模式下执行代码

xml - MinOccurs 0 和 nillable true

c# - FTPClient 将文件从 Linux 移动到 Windows。知道他们什么时候结束发电

c# - 运行时带有黄色横幅的用户帐户控制消息 .msi 由 wix 安装程序创建