开发者

.net schema validation

I am experiencing a problem with validating an xml file against a schema which was generated by svcutil. For the purpose of this question please see below a snippet of code which contains only a simplified XSD schema and the XML document that I am trying to validate:

Imports System.Xml.Schema

Module Main

    Dim errors As Boolean = False

    Sub Main()

        Try

            Dim xsdMarkup As XElement = _
              <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:tns="http://zen/myservices" targetNamespace="http://zen/myservices">

                  <xs:element name="Car" type="tns:CarType"/>

                  <xs:complexType name="CarType">
                      <xs:sequence>
                          <xs:element name="Make" minOccurs="1" maxOccurs="1"/>
                          <xs:element name="Model" minOccurs="1" maxOccurs="1"/>
                      </xs:sequence>
                  </xs:complexType>

              </xs:schema>
            Dim schemas As XmlSchemaSet = New XmlSchemaSet()
            schemas.Add("http://zen/myservices", xsdMarkup.CreateReader)

            Dim doc1 As XDocument = _
             <?xml version='1.0'?>
             <Car>
                 <Makee>content1</Makee>
                 <Model>content1</Model>
             </Car>


            Console.WriteLine("Validating doc1")
            errors = False
            doc1.Validate(schemas, AddressOf XSDErrors)
            Console.WriteLine("doc1 {0}", IIf(errors = True, "did not validate", "validated"))


        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try

        Console.WriteLine("Hit <ENTER> to exit...")
        Console.ReadKey()

    End Sub

    Private Sub XSDErrors(ByVal o As Object, ByVal e As开发者_运维技巧 ValidationEventArgs)
        Console.WriteLine("{0}", e.Message)
        errors = True
    End Sub

End Module

The validation in this particular case should fail (the 'Make' element has been misspelled). Interestingly enough though it passes.

Any ideas what am I missing in this code?

Your help is appreciated.

Zen


All set. I resolved the issue myself. I had accidentally left out the namespaces definition in the XML being validated:

<?xml version='1.0'?>          
<Car>              
    <Makee>content1</Makee>              
    <Model>content1</Model>          
</Car> 

should have been:

<?xml version='1.0'?>
<tns:Car xmlns:tns="http://zen/myservices">
    <Makee>content1</Makee>
    <Model>content1</Model>
</tns:Car>

Validation is failing now as expected.

Zen

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜