c# - Full Framework 和 .NET Core 的 xml 架构编译的不同行为

标签 c# .net xml .net-core xsd-validation

这是我的验证码:

string xsdPath = "base.xsd";
XDocument doc = XDocument.Load(xmlPath);
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("http://some.domain.org", xsdPath);
schemas.Compile();
bool isValid = true;
doc.Validate(schemas, (o, e) => {
    res.AddMessage(MessageSeverities.Error, $"{e.Severity}:{e.Message}");
    isValid = false;
});
if ( isValid ) {
    res.AddMessage(
        MessageSeverities.Notice, 
        $"{formFile.FileName} is valid!");
}

此代码在桌面应用程序 (.net 4.6) 中使用时运行良好

代码在 .net core asp 2.1 Controller 中使用时失败,schemas.Compile(); 引发以下异常:

XmlSchemaException: Type 'http://some.domain.org:tAccountingItemTypes' is not declared.

似乎相关的架构文件没有加载到 asp 核心应用程序中。如何强制加载相关模式?

模式是:

基础.xsd

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema 
    targetNamespace="http://some.domain.org" 
    xmlns="http://some.domain.org"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    elementFormDefault="qualified">

    <xs:include id="enums" schemaLocation="enums.xsd"/>

    <xs:complexType name="tAccountingLines">
      <xs:sequence>
        <xs:element name="AccountingLine" type ="tAccountingLine"></xs:element>
      </xs:sequence>
    </xs:complexType>

    <xs:complexType name="tAccountingLine">
      <xs:sequence>
        <xs:element name="AccountingType" type="tAccountingItemTypes"></xs:element>     
        </xs:element>
      </xs:sequence>    
    </xs:complexType>
</xs:schema>

枚举.xsd

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema 
  targetNamespace="http://some.domain.org" 
  xmlns="http://some.domain.org"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  elementFormDefault="qualified">

  <xs:simpleType name="tAccountingItemTypes">
    <xs:restriction base="xs:string">
      <xs:enumeration value="V1"/>
      <xs:enumeration value="V2"/>
      <xs:enumeration value="V3"/>
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

最佳答案

我刚刚试过了,它没有加载包含的架构的原因是它用来加载它的解析器是 null。这应该修复它:

schemas.XmlResolver = new XmlUrlResolver();

我做了一些挖掘,发现这是 Desktop 和 Core 之间已知的行为变化,即 documented here :

If the schema being added imports another schema through external URI, Core does not allow resolving that URI by default while Desktop does. To allow the resolution on Core, the following needs to be called before adding the schema: AppContext.SetSwitch("Switch.System.Xml.AllowDefaultResolver", true);

显然,除了开关之外,您还可以显式设置解析器,这样您就不会使用默认值。

关于c# - Full Framework 和 .NET Core 的 xml 架构编译的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54764271/

相关文章:

c# - ITextSharp 将文本插入现有的 pdf

javascript - Kendo html 编辑器

.net - 如何阻止异常警报发狂

c# - 在 .NET 线程中花费了多少时间?

c# - EntityFramework 将新对象添加到集合中

sql - 使用带有命名空间的 SQL Server 2008 从 XML 中选择值

c# - 动态更改母版页

.net - 如何在 vb.net 的 XML 文件生成中使用特殊字符,如 '<' 或 '&'

java - 使用 testng.xml 使用 Maven 运行单个 TestNG 测试

c# - 如何在 ASP.NET 中使用配置文件?