私がやろうとしているのは、XSD に対して XML を検証することです。これはすべて非常に簡単ですが、名前空間のない XML には問題があります。C# は、名前空間が XSD のターゲット名前空間と一致する場合にのみ xml を検証します。これは正しいように見えますが、名前空間を持たない XML、または SchemaSet とは異なる名前空間を持つ XML では、例外が発生するはずです。これを達成するためのプロパティまたは設定はありますか? または、xml の xmlns 属性を読み取って名前空間を手動で取得する必要がありますか?
クリアする例:
コード:
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("http://example.com", @"test.xsd");
settings.Schemas.Add("http://example.com/v2", @"test2.xsd");
settings.ValidationType = ValidationType.Schema;
XmlReader r = XmlReader.Create(@"test.xml", settings);
XmlReader r = XmlReader.Create(new StringReader(xml), settings);
XmlDocument doc = new XmlDocument();
try
{
doc.Load(r);
}
catch (XmlSchemaValidationException ex)
{
Console.WriteLine(ex.Message);
}
XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com" targetNamespace="http://example.com" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="test">
<xs:annotation>
<xs:documentation>Comment describing your root element</xs:documentation>
</xs:annotation>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]+\.+[0-9]+" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:schema>
有効な XML:
<test xmlns="http://example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</test>
XML が無効です。これは検証されません:
<hello xmlns="http://example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</hello>
エラー: The 'http://example.com:hello' element is not declared
。
無効な XML ですが、名前空間が存在しないため検証されます:
<hello xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</hello>
どうすればこれを修正できますか?
どんな助けでも大歓迎です。