我有这个非常简单的XSD模式

<?xml version = "1.0" encoding = "UTF-8"?>
<schema xmlns = "http://www.w3.org/2001/XMLSchema"
     targetNamespace = "http://my.domain/xmlschemas/message"
     xmlns:mmm = "http://my.domain/xmlschemas/message"
     xmlns:ds = "http://www.w3.org/2000/09/xmldsig#"
     xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
     elementFormDefault = "qualified">
    <import namespace = "http://www.w3.org/2000/09/xmldsig#" schemaLocation = "xmldsig-core-schema.xsd"/>
  <element name = "message">
        <complexType>
            <sequence>
                 <element name = "Signature" type = "ds:SignatureType" minOccurs = "0" maxOccurs = "unbounded"/>
            </sequence>
        </complexType>
    </element>
</schema>


存储为我的Visual Studio 2010 C#项目以及从xmldsig-core-schema.xsd下载的www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd的嵌入式资源。

我想针对这个XSD模式验证我的文档。我的文件:

<?xml version="1.0" encoding="UTF-8"?>
<message xmlns="http://my.domain/xmlschemas/message">
</message>


我使用XmlDocument.Validate(...)方法通过这种方式进行验证:

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(inputStream); //XML document loads correctly...

Assembly myAssembly = Assembly.GetExecutingAssembly();
using (Stream schemaStream = myAssembly.GetManifestResourceStream("XmlSigTest.Resources.message.xsd"))
{
     XmlSchema schema = XmlSchema.Read(schemaStream, null);
     doc.Schemas.Add(schema); //XSD schema loads correctly
}

bool ok = true;
doc.Validate((s, e) => //throws Exception!!!
{
     ok = false;
});


此代码在doc.Validate(...)中引发异常,并显示消息:Type 'http://www.w3.org/2000/09/xmldsig#:SignatureType' is not declared。但是,Visual Studio XML编辑器中没有警告或错误,我可以在Visual Studio XML Schema Explorer中看到SignatureType。为什么会引发此异常?我该怎么办?

最佳答案

我自己解决了这个问题。我的XSD的这一行效果不佳:

<import namespace = "http://www.w3.org/2000/09/xmldsig#" schemaLocation = "xmldsig-core-schema.xsd"/>


我以为doc.Validate(...)会自动下载或找到所有引用的外部架构。 (在我的情况下为xmldsig-core-schema.xsd)。好吧...不会。

我必须将引用的架构手动添加到doc.Schemas,此后一切正常。

结果代码:

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(inputStream);

Assembly myAssembly = Assembly.GetExecutingAssembly();
foreach (string resource in new string[] {"message.xsd", "xmldsig-core-schema.xsd"}) {
      using (Stream schemaStream = myAssembly.GetManifestResourceStream("XmlSigTest.Resources." + resource))
      {
             XmlSchema schema = XmlSchema.Read(schemaStream, null);
             doc.Schemas.Add(schema);
      }
}

bool ok = true;
doc.Validate((s, e) =>
{
     ok = false;
});

10-05 22:01