我想了解如何驗證其中有多個名稱空間的XML文檔,但沒有變得很遠。由於我在做什麼一個簡單的例子,我有一個命名空間中定義這樣的「根」元素:如何使用名稱空間來驗證XML
文件:「root.xsd」
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:complexType name="root"/>
<xs:element name="root">
<xs:complexType>
<xs:complexContent>
<xs:extension base="root">
<xs:sequence>
<xs:element ref="allowedChild"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
<xs:complexType name="allowedChild"/>
<xs:element name="allowedChild" type="allowedChild"/>
</xs:schema>
然後一個「孩子」這樣的定義的元素:
文件: 「child.xsd」
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:include schemaLocation="root.xsd"/>
<xs:complexType name="child">
<xs:complexContent>
<xs:extension base="allowedChild"/>
</xs:complexContent>
</xs:complexType>
<xs:element name="child" type="child" substitutionGroup="allowedChild"/>
</xs:schema>
而且我想VA的XML lidate,我想應該是這樣的:
<root xmlns="root.xsd">
<child xmlns="child.xsd"/>
</root>
如果我嘗試在XMLSPY驗證這一點,我得到「無法找到這個文件實例中的支持的架構類型(DTD,W3C架構)的參考。」
我也試着寫一些C#驗證(這是我的終極目標)。我的代碼如下所示:
static void Main(string[] args)
{
using (var stream = new StreamReader("Example.xml"))
{
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.ValidationEventHandler += MyValidationEventHandler;
schemaSet.XmlResolver = new XmlUrlResolver();
schemaSet.Add(null, "root.xsd");
XmlReaderSettings settings = new XmlReaderSettings()
{
ValidationType = ValidationType.Schema,
ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings,
Schemas = schemaSet,
};
settings.ValidationEventHandler += MyValidationEventHandler;
XmlReader reader = XmlReader.Create(stream, settings);
while (reader.Read())
{
}
}
}
static void MyValidationEventHandler(object sender, ValidationEventArgs e)
{
}
但是這給了我下面的驗證錯誤:
Could not find schema information for the element 'root.xsd:root'.
Could not find schema information for the element 'child.xsd:child'.
我希望在XmlUrlResolver會發現XSD文件(保存在同一文件夾中),但我猜猜它沒有這樣做?
我的目標是有多個child.xsd類型的文件,即編譯時間後產生的,只有在運行時解決。這可能嗎?
您需要在模式中使用'targetNamespace'。這些命名空間是你應該在'xmlns'中引用的。 –