使用带有包含的XSD

Ric*_*ugh 17 c# xml xsd xml-namespaces

这是一个XSD:

<?xml version="1.0"?>
<xsd:schema 
elementFormDefault='unqualified' 
attributeFormDefault='unqualified' 
xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
>

  <xsd:simpleType name='TheSimpleType'>
    <xsd:restriction base='xsd:string' />
  </xsd:simpleType>
</xsd:schema>
Run Code Online (Sandbox Code Playgroud)

这是第二个包含上述XSD的XSD:

<?xml version="1.0" encoding="UTF-8" ?>
<xsd:schema 
elementFormDefault='unqualified' 
attributeFormDefault='unqualified' 
xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
targetNamespace='a'
xmlns='a'
>

  <xsd:include schemaLocation='Include.xsd' />

  <xsd:element name = "TheElement" >
  <xsd:complexType>
  <xsd:attribute name="Code" type="TheSimpleType" use="required"/>
  </xsd:complexType>
  </xsd:element>
</xsd:schema>
Run Code Online (Sandbox Code Playgroud)

我需要将(第二个)XSD读入C#并且:

  1. 检查它是否是有效的XSD,并且
  2. 验证文件.

下面是一些要在schemata中读取的C#:

    XmlSchemaSet schemaSet = new XmlSchemaSet();
    foreach (string sd in Schemas)
    {
        using (XmlReader r = XmlReader.Create(new FileStream(sd, FileMode.Open)))
        {
            schemaSet.Add(XmlSchema.Read(r, null));
        }
    }
    schemaSet.CompilationSettings = new XmlSchemaCompilationSettings();
    schemaSet.Compile();
Run Code Online (Sandbox Code Playgroud)

.Compile()失败,因为"Type'a:TheSimpleType'未声明,或者不是简单类型."

但是,它适用于:

  • 命名空间将从架构中删除,或
  • 命名空间被添加到include中.

问题是:如何在不编辑架构的情况下让C#接受它?

我怀疑问题是虽然我已将两个schemata都放入XmlSchemaSet中,但我仍然需要告诉C#一个被包含在另一个中,即它没有为自己解决问题.实际上,如果我只告诉XmlSchemaSet有关主XSD(而不是include)(两者都没有(或带有)名称空间),那么"Type"TheSimpleType'未声明,或者不是简单类型."

因此,这似乎是一个关于解决的问题包括:如何?!

Ric*_*ugh 27

问题在于打开架构以便在线读取的方式:

XmlReader.Create(new FileStream(sd, FileMode.Open)
Run Code Online (Sandbox Code Playgroud)

XmlResolver在我看到包含文件的路径如何解析之前,我必须自己编写:它来自可执行文件的目录,而不是来自父模式的目录.问题是父模式没有设置其BaseURI.以下是必须打开架构的方法:

XmlReader.Create(new FileStream(pathname, FileMode.Open, FileAccess.Read),null, pathname)
Run Code Online (Sandbox Code Playgroud)


Jor*_*dão 6

您可以使用XmlSchema.Includes它们将它们链接在一起.然后,您只需要将主模式添加到模式集:

var includeSchema = XmlSchema.Read(XmlReader.Create(...), null);
var mainSchema = XmlSchema.Read(XmlReader.Create(...), null);

var include = new XmlSchemaInclude();
include.Schema = includeSchema;
mainSchema.Includes.Add(include);

var schemaSet = new XmlSchemaSet();
schemaSet.Add(mainSchema);
schemaSet.Compile();
Run Code Online (Sandbox Code Playgroud)

  • 好的,好的.但是现在假设我必须在运行时确定所有包含,即,我给你一个带有包含的任意XSD,你必须去取它们全部. (2认同)