locked
xml string validation with xsd RRS feed

  • Question

  • Hi,

    I get xml as string from database. I have xsd file. In C#, I need to validate this xml string against xsd schema and send to IBM MQ service. If validation is not successful, I need to catch errors.

    Any suggestions or links to do it in C#.

    Thanks

    Tuesday, April 10, 2018 7:55 PM

Answers

  • Hello Spunny, the xsd is case sensitive so MESSAGE is not Message.

    <?xml version="1.0" encoding="utf-8"?>
    <Message xmlns="http://tempuri.org/SchemaMsg.xsd"         
             MessageID="1" ApplicationName="HelloWorld" MessageCreationTime="2018-04-09T17:54:47.85" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Clients ChildCount="1">
        <Client>
          <ACTION>Add</ACTION>
          <SHORTNAME>xxx</SHORTNAME>
          <LONGNAME>DataForms Inc</LONGNAME>
          <TYPE>DataMassageA</TYPE>
        </Client>
      </Clients>
    </Message>


    Cheers, Jeff

    Thursday, April 12, 2018 9:40 PM

All replies

  • hello Spunny,

    Fortunately this is supported in the core libraries and several posts are available showing how to do xml validation using an xsd:

    https://www.c-sharpcorner.com/article/how-to-validate-xml-using-xsd-in-c-sharp/

    https://stackoverflow.com/questions/751511/validating-an-xml-against-referenced-xsd-in-c-sharp

    https://forums.asp.net/t/2066719.aspx?Validate+input+XML+with+XSD+in+c+


    Cheers, Jeff

    Wednesday, April 11, 2018 3:19 AM
  • Hi Spunny,

    Thank you for posting here.

    For your question, you could refer to the MSDN article. It shows a simple example about how to validate with XSD.

    https://docs.microsoft.com/en-us/dotnet/standard/data/xml/xml-schema-xsd-validation-with-xmlschemaset

    And here is the similar thread I done before about validate with XSD with example.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/2e2e9851-21d2-42a3-8026-51b19ed82148/how-to-validate-xml-when-reading-xml-data-using-xml-reader-or-xml-textreader-class-?forum=csharpgeneral

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, April 11, 2018 8:31 AM
  • Thank you Jeff and wendy. I needed a code for xml string. I tried below code. It is erroring out. Can you please take a look at it.

    below is my xml which I have it in string variable. I have xsd and I need to validate my xml with xsd. when I try below c# code I error on line document.LoadXml(xml). Not sure how to trouble shoot. Are my nam spaces and schema locations correct in both? since we load xsd using path, do we need xmlns and xsi:schemaLocation attributes. I am new to xml. Why do we need all those?

    My XML looks like this:

    <?xml version="1.0" encoding="utf-8"?>
    <MESSAGE xmlns="http://tempuri.org/SchemaMsg.xsd" xsi:schemaLocation="http://tempuri.org/SchemaMsg.xsd" MessageID="1" ApplicationName="HelloWorld" MessageCreationTime="2018-04-09T17:54:47.85" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <CLIENTS ChildCount="1">
        <CLIENT>
          <ACTION>Add</ACTION>
          <SHORTNAME>xxx</SHORTNAME>
          <LONGNAME>DataForms Inc</LONGNAME>
          <TYPE>DataMassage</TYPE>           
        </CLIENT>    
      </CLIENTS>
     </MESSAGE>

    XSD:

        

    <?xml version="1.0" encoding="utf-8

     try
                { 
                        string xsdPath = "C:\\TestApps\\WebApplication1\\WebApplication1\\bin\\MessageSchema.xsd";
                        XmlReader schema = XmlReader.Create(xsdPath);
                        XmlDocument document = new XmlDocument();
                        document.LoadXml(xml);
                        document.Schemas.Add("", schema);
                    ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
                    document.Validate(eventHandler);
                    string var;
                    if (validationErrors == "")
                        var = "success";
                    else
                        var = "Failure";
                }
                catch (Exception)
                {
                    throw;
                }

    "?>
    <xsd:schema id="MessageSchema" targetNamespace="http://tempuri.org/SchemaMsg.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/SchemaMsg.xsd" xmlns:mstns="http://tempuri.org/SchemaMsg.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="Message" type="MessageType"/>
      <xsd:complexType name="MessageType">
        <xsd:choice minOccurs="1" maxOccurs="unbounded">
          <xsd:sequence>        
            <xsd:element name="Clients" type="ClientsType" minOccurs="0" maxOccurs="1" />        
          </xsd:sequence>
        </xsd:choice>
        <xsd:attribute name="MessageID" type="xsd:string"/>
        <xsd:attribute name="ApplicationName" type="xsd:string"/>
        <xsd:attribute name="MessageCreationTime" type="xsd:dateTime"/>
      </xsd:complexType>

      <xsd:complexType name="ClientsType">
        <xsd:sequence minOccurs="1" maxOccurs="unbounded">
          <xsd:element name="Client" type="ClientType"/>
        </xsd:sequence>
        <xsd:attribute name="ChildCount" type="xsd:int" />
      </xsd:complexType>  

      <xsd:complexType name="ClientType">
        <xsd:sequence>
          <xsd:element name="ACTION" type="ActionTypes" />
          <xsd:element name="SHORTNAME" type="xsd:string" />
          <xsd:element name="LONGNAME" type="xsd:string" />
          <xsd:element name="TYPE" type="ClientTypes" />            
        </xsd:sequence>
      </xsd:complexType>  
      <xsd:simpleType name="ActionTypes">
        <xsd:restriction base="xsd:string">
          <xsd:enumeration value="Add"/>
          <xsd:enumeration value="Update"/>
          <xsd:enumeration value="Delete"/>
        </xsd:restriction>
      </xsd:simpleType>
      <xsd:simpleType name="ClientTypes">
        <xsd:restriction base="xsd:string">
          <xsd:enumeration value="DataMassageA" />
          <xsd:enumeration value="DataMassageB" />
        </xsd:restriction>
      </xsd:simpleType>
    </xsd:schema>

    C# code to validate xml against xsd

     protected void Button1_Click(object sender, EventArgs e)
            {

    string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <MESSAGE xmlns=\"http://tempuri.org/SchemaMsg.xsd\" xsi:schemaLocation=\"http://tempuri.org/SchemaMsg.xsd\" MessageID=\"1\" ApplicationName=\"HelloWorld\" MessageCreationTime=\"2018-04-09T17:54:47.85\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
      <CLIENTS ChildCount=\"1\">
        <CLIENT>
          <ACTION>Add</ACTION>
          <SHORTNAME>xxx</SHORTNAME>
          <LONGNAME>DataForms Inc</LONGNAME>
          <TYPE>DataMassage</TYPE>           
        </CLIENT>    
      </CLIENTS>
     </MESSAGE>";

     try
                { 
                        string xsdPath = "C:\\WebApplication1\\bin\\MessageSchema.xsd";
                        XmlReader schema = XmlReader.Create(xsdPath);
                        XmlDocument document = new XmlDocument();
                        document.LoadXml(xml);
                        document.Schemas.Add("", schema);
                    ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
                    document.Validate(eventHandler);
                    string var;
                    if (validationErrors == "")
                        var = "success";
                    else
                        var = "Failure";
                }
                catch (Exception)
                {
                    throw;
                }

    }

     private void ValidationEventHandler(object sender, ValidationEventArgs e)
            {
                validationErrors += e.Message + "<br />";
            }

    Thursday, April 12, 2018 3:56 AM
  • Hello Spunny, the xsd is case sensitive so MESSAGE is not Message.

    <?xml version="1.0" encoding="utf-8"?>
    <Message xmlns="http://tempuri.org/SchemaMsg.xsd"         
             MessageID="1" ApplicationName="HelloWorld" MessageCreationTime="2018-04-09T17:54:47.85" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Clients ChildCount="1">
        <Client>
          <ACTION>Add</ACTION>
          <SHORTNAME>xxx</SHORTNAME>
          <LONGNAME>DataForms Inc</LONGNAME>
          <TYPE>DataMassageA</TYPE>
        </Client>
      </Clients>
    </Message>


    Cheers, Jeff

    Thursday, April 12, 2018 9:40 PM