2016-01-08 18 views
2

我有一個非常簡單的XSD架構「類型 'http://www.w3.org/2000/09/xmldsig#:SignatureType' 未聲明」 在XmlDocument.Validate(...)

<?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。爲什麼拋出這個異常?我該怎麼辦?

回答

0

我自己解決了這個問題。我的XSD的這條線沒有工作:

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

我想doc.Validate(...)將下載或自動查找所有引用外部模式。 (在我的情況下爲xmldsig-core-schema.xsd)。那麼......它不會。

我不得不手動添加引用的模式到doc.Schemas,從那以後它就OK了。

結果代碼:

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; 
});