"键入' http://www.w3.org/2000/09/xmldsig#:SignatureType'没有宣布"在XmlDocument.Validate(...)中

时间:2016-01-08 14:37:35

标签: c# xml validation xsd xsd-validation

我有这个非常简单的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 Editor中没有警告或错误,我可以在Visual Studio XML Schema Explorer中看到SignatureType。为什么抛出这个异常?我该怎么办?

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题。我的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;
});