私がしようとしているのは、XSDに対してXMLを検証することです。これはすべて簡単ですが、名前空間のないXMLに問題があります。 C#は、ネームスペースがXSDのターゲットネームスペースと一致する場合にのみxmlを検証します。これは正しく見えますが、名前空間やSchemaSetのないXMLでは例外が発生します。これを達成するためのプロパティーや設定がありますか?または、xmlのxmlns属性を読み取って手動で名前空間を取得する必要がありますか?.NETのXML検証と名前空間
clearifyする例:
コード:
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>
エラー:。
無効なXMLが、名前空間が存在しないため、検証します:
<hello xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</hello>
私はこれをどのように修正することができますか?
ご迷惑をおかけして申し訳ございません。私は見つけることができます
いいえ - 私はこれを試しましたが、バリデーターはハンドラをまったく起動していません。 .Netはこれを警告とはみなしていないようです。 –