問題描述
這是一個 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>
這是第二個 XSD,包括上面的一個:
Here is a second XSD that includes the one above:
<?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>
我需要將(第二個)XSD 讀入 C# 并且:
I need to read the (second) XSD into C# and:
- 檢查它是否是有效的 XSD,并且
- 根據它驗證文檔.
這里有一些 C# 可以在架構中閱讀:
Here is some C# to read in the schemata:
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();
.Compile() 失敗,因為類型 'a:TheSimpleType' 未聲明,或者不是簡單類型."
The .Compile() fails because "Type 'a:TheSimpleType' is not declared, or is not a simple type."
但是,如果滿足以下任一條件,它就會起作用:
However, it works if either:
- 命名空間已從架構中移除,或者
- 命名空間被添加到包含中.
問題是:如何在不編輯模式的情況下讓 C# 接受它?
The question is: how do I get C# to accept it without editing the schemata?
我懷疑問題在于,雖然我已將兩個模式都放入 XmlSchemaSet,但我仍然需要告訴 C# 一個包含在另一個中,即它自己并沒有解決.事實上,如果我只告訴 XmlSchemaSet 主 XSD(而不是包含)(都沒有(或有)命名空間),那么類型 'TheSimpleType' 沒有聲明,或者不是簡單類型."
I suspect the problem is that although I have put both schemata into the XmlSchemaSet, I still need to tell C# that one is included into the other, i.e., it hasn't worked it out for itself. Indeed, if I only tell the XmlSchemaSet about the main XSD (and not the include) (both without (or with) namespaces) then "Type 'TheSimpleType' is not declared, or is not a simple type."
因此這似乎是一個關于解決的問題包括:如何?!
Thus this seems to be a question about resolving includes: how?!
推薦答案
問題在于在線打開模式讀取的方式:
The problem is with the way the schema is opened for reading on the line:
XmlReader.Create(new FileStream(sd, FileMode.Open)
我必須編寫自己的 XmlResolver
才能看到如何解析包含文件的路徑:它來自可執行文件的目錄,而不是來自父架構的目錄.問題是父模式沒有得到它的 BaseURI 集.以下是必須打開模式的方式:
I had to write my own XmlResolver
before I could see how the paths to the include files were being resolved: it was from the directory of the executable and not from the directory of the parent schema. The problem is that the parent schema was not getting its BaseURI set. Here's how the schema must be opened:
XmlReader.Create(new FileStream(pathname, FileMode.Open, FileAccess.Read),null, pathname)
這篇關于將 XSD 與包含一起使用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!