简体   繁体   中英

Xml validation using xsd not caught

I've been trying to validate my xml file using XmlSchemaSet but for some reason the error is not getting caught when I read the xml. I'm almost certain that the problem is not in my xml or xsd because when I have the xml open in visual studio it actually tells me that my attribute contains an invalid value.

Xml:

<Test xmlns:testns="http://schemas.testnamespace.com/" xmlns="http://schemas.testnamespace.com/"
  testns:foo="-903" />

xsd (example taken from Microsoft's documentation on xsd:union)

<?xml version="1.0"?>

<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://schemas.testnamespace.com/"
    xmlns="http://schemas.testnamespace.com/"
    elementFormDefault="qualified"
    attributeFormDefault="qualified" >

    <xs:element name="Test" >
        <xs:complexType>

            <xs:attribute name="foo">
                <xs:simpleType>
                    <xs:union memberTypes="fontbynumber fontbystringname" />
                </xs:simpleType>
            </xs:attribute>

        </xs:complexType>
    </xs:element>

    <xs:simpleType name="fontbynumber">
        <xs:restriction base="xs:positiveInteger">
            <xs:maxInclusive value="72"/>
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="fontbystringname">
        <xs:restriction base="xs:string">
            <xs:enumeration value="small"/>
            <xs:enumeration value="medium"/>
            <xs:enumeration value="large"/>
        </xs:restriction>
    </xs:simpleType>

</xs:schema>

Validation code:

XmlSchemaSet sc = new XmlSchemaSet();

//Passing null instead of the namespace doesn't change anything
sc.Add("http://schemas.testnamespace.com/", "Bar.xsd");
sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
sc.Compile();

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
//I've tried all combinations of ValidationFlags and it doesn't change anything
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
settings.Schemas = sc;

using(XmlReader reader = XmlReader.Create(path, settings))
{
    while(reader.Read()) ;
}

I feel like the problem might be in union because whenever I used union or list it never catches any error but as soon as I just use restriction without union or list it catches the error..

Please help :(

Testing on .net 2.0 & 4.61 and it works as expected.

You got the right file in the 'path' variable?

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM