XML Schema not Validating XML Fragment

I'm trying to validate the following xml  fragment (Figure A.) against a schema document (Figure B.) that i have created and tested through a seperate XML Validator utility that so i know that the validation works outside of the asp.net code (Figure C.). The validation does return XML exceptions for well-formed stcructure but doesn't return any schema validation exceptions if i force an error in the xml. Any ideas why the XML fragment isn't being validated by the schema??? I've tried just about everything :(

=========================
A. XML Fragment to Validate
=========================


<VAS>
  <Identification>
    <UniqueID>2A79F1D</UniqueID>
    <VASID>2A79F1D9-745D-4294-BD99-DEAD2026898A</VASID>
  </Identification>
  <Ecommerce>
  </Ecommerce>
  <Web>
  </Web>
  <Call>
  </Call>
  <Dispositions>
    <DispositionCode>PURCH</DispositionCode>
  </Dispositions>
</VAS>

=========================
B. Schema uses to validate above XML
=========================


<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="VASProviderXMLSchema"
targetNamespace="http://localhost/VASClientService_WEB"
elementFormDefault="qualified"
xmlns="http://localhost/VASClientService_WEB"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="VAS">
    <xs:complexType>
      <xs:sequence>

        <xs:element name="Identification">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="UniqueID">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:length value="36" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
              <xs:element name="VASID">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:length value="36" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

        <xs:element name="Ecommerce">
          <xs:complexType>
            <xs:sequence>
              <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

        <xs:element name="Web">
          <xs:complexType>
            <xs:sequence>
              <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

        <xs:element name="Call">
          <xs:complexType>
            <xs:sequence>
              <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

        <xs:element name="Dispositions">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="DispositionCode">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:enumeration value="PURCH"/>
                    <xs:enumeration value="RETURN/REFUND"/>
                    <xs:enumeration value="CANCEL"/>
                    <xs:enumeration value="INTEREST"/>
                    <xs:enumeration value="FREE"/>
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

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

 </xs:schema>

====================================
C. VB code that performs the validation
====================================


          Try
            'Create the XML fragment to be parsed.
            Dim xmlFrag As String = XMLData

            'Add the schema to XmlSchemaSet
            Dim XMLDataSchema As XmlSchemaSet = New XmlSchemaSet

            XMLDataSchema.Add("http://localhost/VASClientService_WEB", "http://localhost/VASClientService_WEB/VASProviderXMLSchema.xsd")

            'set XMLReader settings
            Dim XMLDataReaderSettings As XmlReaderSettings = New XmlReaderSettings()

            XMLDataReaderSettings.ValidationType = ValidationType.Schema
            XMLDataReaderSettings.Schemas = XMLDataSchema
            'XMLDataReaderSettings.ValidationFlags = XMLDataReaderSettings.ValidationFlags or XmlSchemaValidationFlags.ProcessInlineSchema
            'XMLDataReaderSettings.ValidationFlags = XMLDataReaderSettings.ValidationFlags or XmlSchemaValidationFlags.ProcessSchemaLocation
            'XMLDataReaderSettings.ValidationFlags = XMLDataReaderSettings.ValidationFlags or XmlSchemaValidationFlags.ReportValidationWarnings
            'XMLDataReaderSettings.ValidationFlags = XMLDataReaderSettings.ValidationFlags or XmlSchemaValidationFlags.ProcessIdentityConstraints
            XMLDataReaderSettings.ConformanceLevel = ConformanceLevel.Auto
            XMLDataReaderSettings.XmlResolver = New XmlUrlResolver

            'Define Name Table and XmlNamespaceManager
            'XMLDataReaderSettings.NameTable = New NameTable
            'Dim nsm As New XmlNamespaceManager(XMLDataReaderSettings.NameTable)
            'nsm.AddNamespace("xs", "http://localhost/VASClientService_WEB")

            'Create the XmlParserContext.
            Dim context As New XmlParserContext(Nothing, Nothing, "en", XmlSpace.Default)

            'Add handler
            AddHandler XMLDataReaderSettings.ValidationEventHandler, AddressOf ValidationEventHandle

            'Implement the reader.
            Dim XMLDataReader As XmlReader = XmlReader.Create(New StringReader(xmlFrag), XMLDataReaderSettings, context)

            'Iterate through each node.
            'Throw exception if a error is detected.
            While XMLDataReader.Read
                'Do Nothing
            End While

            Return "Completed validating xml validation"

        Catch XmlExp As XmlException

            Return XmlExp.Message

        Catch XmlSchExp As XmlSchemaException

            Return XmlSchExp.Message

        Catch GenExp As Exception

            Return GenExp.Message

        End Try


0
funkycowboy
6/1/2007 5:20:30 PM
asp.net.xml-datasource 7181 articles. 0 followers. Follow

2 Replies
890 Views

Similar Articles

[PageSpeed] 5

Hi, 

when every an exception is occured  ValidationEventHandle  function is called. so you don't see any exceptions.

you can see the error messages in ValidationEventHandle   function.

 

Thanks,

Kiran 

 


Don't forget to click "Mark as Answer" on the post that helped you.
0
kalvagadda
6/2/2007 4:18:10 PM

Hi  funkycowboy ,

Welcome to ASP.NET and thanks for your post.

Please try this schema:

 

<xs:schema id="VASProviderXMLSchema" 
targetNamespace="http://localhost/VASClientService_WEB" 
elementFormDefault="qualified" 
xmlns="http://localhost/VASClientService_WEB" 
xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="VAS">
    <xs:complexType>
      <xs:sequence>

        <xs:element name="Identification">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="UniqueID">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:length value="7" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
              <xs:element name="VASID">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:length value="36" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

        <xs:element name="Ecommerce">
          <xs:complexType>
            <xs:sequence>
              <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

        <xs:element name="Web">
          <xs:complexType>
            <xs:sequence>
              <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

        <xs:element name="Call">
          <xs:complexType>
            <xs:sequence>
              <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

        <xs:element name="Dispositions">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="DispositionCode">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:enumeration value="PURCH"/>
                    <xs:enumeration value="RETURN/REFUND"/>
                    <xs:enumeration value="CANCEL"/>
                    <xs:enumeration value="INTEREST"/>
                    <xs:enumeration value="FREE"/>
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

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

</xs:schema>

 I removed targetNameSpace and change UniqueID from 36 to 7 (according to <UniqueID>2A79F1D</UniqueID>  ).

I am using below C# code:

        XmlReaderSettings settings = new XmlReaderSettings();

        string booksSchemaFile = Path.Combine(Request.PhysicalApplicationPath, "xsd4.xsd");
        settings.Schemas.Add(null, XmlReader.Create(booksSchemaFile));

        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;

        settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
        settings.IgnoreWhitespace = true;

        settings.IgnoreComments = true;
        string booksFile = Path.Combine(Request.PhysicalApplicationPath, "test74.xml");
        XmlReader reader = null;
        try
        {
            using (reader = XmlReader.Create(booksFile, settings))
            {

                while (reader.Read())
                {

                }
            }
        }
        finally
        {
            reader.Close();
        }
    }

    void settings_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
    {

        Response.Write(e.Message);

    }

 

Please free to ask if above code doesn't work.Thanks.


NOTE:If you find my response contains a reference to a third party World Wide Web site, I am providing this information as a convenience to you.Microsoft does not control these sites and has not tested any software or information found on these sites; therefore,Microsoft cannot make any representations regarding the quality,safety, or suitability of any software or information found there.
__________________________________________________

Sincerely,
Young Fang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
0
Young
6/5/2007 3:35:30 AM
Reply:

Similar Artilces:

XML in, XML out
Hi All (and a happy holiday to those that will get a break), I am trying to read in an XML file of addresses. I need to remove all the address data from the file where code =~ /^000/ (there are none in the example data below). I need to reproduce that data 'as is', so I need to honour the tag structure, although the order of the tags doesn't need to be honoured. I have been trying to use XML::Simple and I had a go with XML::Smart but I haven't been able to get the results I want. My best effort is below (with XML::Simple). There are a couple of differences ...

XMl to XML
Hello,   I retrieved an XML from the dataset which retrieves data from the table in the database. I need to present the data  in a different structure. Is XSLT the way or are there any other options. please let me know. Thanks!! Yes XSLT is a good choice to convert xml file to other forms. You can take a look at XSLT Tutorial.Sincerely,Young Fang...

Validating XML file with XML schema
I want to be able to edit an XML file in browser. I open the XML file, read its contents and put it into a multi-line textbox for the user to edit it. Now, when the user wants to save the changes by pressing the save -button, I want to check if the XML data still is valid. For this I think the XML schema is perfect, right? Now, how can I write an function that takes a string parameter (which contains the whole XML file data from the textbox) and validates it against a schema file? I created the schema by passing a 100% valid XML file to the Visual Studio´s "Create Schema" tool. The...

XML Schema that allows XML Fragments
I'm writing a little tool that would allow clients to create customizable profiles on my website. The profiles use a special XML language that will be parsed and transformed into an HTML document. A sample XML looks like this:   <websites> <header> <div class="company_websites"> </header> <content> <p> #SITE_NAME </p> </content> <footer> </div> </footer> </websites>  Most elements in the XML allow user to defi...

XMLParseFile: Validating XML File Against XML Schema
I am having problems using the XMLParseFile function to validate an XML file against an XML Schema generated by a source external to our organization. The XML file and XML Schema are stored locally in the same directory. Scenario as follows: 1. Schema received as an Email attachment from an outside source (i.e. external to our organization). 2. Attachment saved to disk: C:\myDirectory\schemaDoc.xsd 3. XML file generated from an external source datawindow using SaveAs method: C:\myDirectory\xmlDoc.xml 4. XMLParseFile first used to c...

write to a xml with a xml schema
Hi, I have a xml schema, and a xml that validate this schema.I want to append new nodes to this xml with code (c#)which is the best form to do this?thanks...

Adding a XML schema to XML schema collection
I used SSEUtil to add a schema to my database but I am having problems.  Used these steps:SSEUtil -c> USE "c:\Rich.mdf"> GO>!RUN Resume.SQL//indicates success>SELECT * FROM SYS.XML_SCHEMA_COLLECTIONS>GO//schema not shown in list> USE master>GO>SELECT * FROM SYS.XML_SCHEMA_COLLECTIONS>GO//schema is shown in the queryIt appears that the schema is not added to the desired database, so when I try to use the schema in Visual Studio, the schema does not appear when I connect to the Rich.mdf database.  Any ideas on what I am doing wrong or why this might be happ...

Xml Schema from xml file
How should i create xml schema from xml file?  Do you mean an XSD?  That's easy--open the XML file in Visual Studio.  There will be a new XML menu button, and one option is to create an XSD.  If you have a lot of files, MS has a little tool at http://msdn.microsoft.com/en-us/vbasic/bb840042.aspx.If my post is your answer, please mark it as the answer. It will bring good karma.Crystal AllianceMy BlogFlorist Blogs  Thanks alot!!  It worked wonderfully...

XML & XML Schema
 Hi Can I use XML natively instead of a XML Schema.The schema is very simple and I would like to see if it's possible to use just XML. <!--W3C Schema generated by XMLSpy v2007 (http://www.altova.com)--> <!--Please add namespace attributes, a targetNamespace attribute and import elements according to your requirements--> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:import namespace="http://www.w3.org/XML/1998/namespace"/> <xs:element name="issue"> <...

Xml schema to Xml file
Is it possible to convert xml schema to xml file.How can i do read&writexmlschema using a dataset with xml schema. I converted a xml file to xml schema in a web appliction project.Then what should be location of shema that i need to give for a dataset I mean dataset.readxmlscheme(server.mappath(??))   Please let me know I am new to this field     dataset.ReadXml(Server.MapPath("xml\ProductList.xml")) will read the xml as well as the schema of thexml file. no need to convert it into schema file while using dataset as it will automatically define the ...

XML::Parser XML::DOM XML::XSLT
------_=_NextPart_001_01C6E0D0.3E27D77A Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable Hi Craig and fellow VMS Perlers, You last wrote about this Fri 3/16/2001 11:24 AM, not counting your very helpful comments on Eisner/Decuserve more recently. One of my colleagues sent me an email requesting that I make XML::XSLT=20 available on VMS. perl 5.8.6, VMS 7.3-2, DECC 7.1 latest ACRTL (version 3) on Alpha XML::XSLT (version 0.48) depends on XML::Parser (version 2.34). This depends on expat (version 2.0.0). I built expat a...

Use an XML Schema to validate an XML files that contains includes.
Is there a way to validate an XML file that is made up by including several other XML files using an XML schema?     Yes, you need to set the included schemas with XmlSchema.Includes property. Pls take a look at: http://msdn2.microsoft.com/en-us/library/system.xml.schema.xmlschema.includes.aspxNOTE:If you find my response contains a reference to a third party World Wide Web site, I am providing this information as a convenience to you.Microsoft does not control these sites and has not tested any software or information found on these sites; therefore,Microsoft cannot make any...

XML to XML transform
Hi all, I have an XML file in which I just want to change a couple of values.  So, the end result is a new file with exactly the same XML structure.  I am new to XML and XSLT, so I thought I'd start off with something simple; I created an xsl file that would just copy the source directly across without modifying the values (I can do this later, once I have the first bit figured) - <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:con="http://eviware.com/soapui/config"><xsl:template match="/"...

Transform XML to XML
I've been trying to transform an XML document to another XML document. The original document is very large (6megs) and the application that needs to use it only needs a fraction of the data. I'm trying to take this mother-of-all XML documents and filter out unwanted nodes. I could probably do this very easily with code by running a few XPath Queries against the document, and placing the results in a new document...however...I have an interest in learning how to do this with XSL. In the past, I've done some pretty basic XML to HTML transformation ans that worked out well. This ti...

Web resources about - XML Schema not Validating XML Fragment - asp.net.xml-datasource

Talking to police about Ghomeshi allegations was validating: Decoutere
One of the women accusing former CBC host Jian Ghomeshi of violent behaviour is encouraging other potential victims not to be afraid of speaking ...

Validating Input and Interprocess Communication
Describes techniques to use and factors to consider to make your code more secure from attack.

Validating team-by-team R and RBI predictions for 2012 AL Edition
Unless you're a big fan of my writing, you may not know that at this time last year, I wrote for a different SB Nation site: the dearly departed ...

"It is important not to create a precedent validating the prohibition of the sale of any object of a ...
"... regardless of the culture concerned... Our goal has always been to showcase Hopi culture and make it accessible to the largest number of ...

Validating the Donald
Validating the Donald by digby In Salon today , I wrote about the right wing media's immigration backlash strategy by validating Donald Trump's ...

Validating your marketing audience
... enjoyed this, please share it with your network! Want to read more like this from Christopher Penn ? Get daily updates now: The post Validating ...

Validating Albert Einstein, physicists make major discovery about the early universe
In the beginning there was the Big Bang. What we know about this time is that the universe was extremely hot, dense and almost uniform; it was ...

Validating Architecture through LINQ Query
... is simple enough to get validated at a glance. But at a glance is not enough. What about defining custom rules that take care of validating ...

From Data to Action – Best Practices for Validating and Optimizing Your Digital Campaigns - comScore ...
In this webinar, comScore Senior Industry Analyst Jason Patterson explores how you can use comScore's validated data to optimize and improve ...

TDD of a WinForm app – Part 5 – Validating the account data
In our last post, we worked on allowing our user to enter new accounts – basically making our AddAccountForm usable. We were able to do that ...

Resources last updated: 1/20/2016 2:58:41 AM