5/15/11

How to Use Xsd in Net

XML Schema Definition, XSD, is the most widely accepted standard for defining the structure of XML documents. Schemas can define restrictions, optional and required attributes within a XML document. .Net allows validation of XML using one or more schemas before processing the content. Validating XML reduces the amount exception handling that must be performed in code and catches errors in the data formatting that might otherwise be overlooked.
  • XML Validation Using XmlReaderSettings

    • 1

      Create a new C# project of the desired type in Visual Studio. If you want to add XML validation to an existing project, you can skip this step.

    • 2

      Open the "Add New Item" dialog box by clicking "Project" and then clicking "Add Class."

    • 3

      Specify a name for the new class that adheres to your coding standards and naming practices.

    • 4

      Right-click the project in the Solution Explorer to display the project menu.

    • 5

      Select "Add Reference" from the menu to display the "Add Reference" dialog box.

    • 6

      Select System.XML from the list of components and then click the "Select" button. Then, click "OK."

    • 7

      Add a method to the new class using the following code:

      private bool ValidateDocument(string xmlFile, string xsdFile)

      {

      XmlReaderSettings settings = new XmlReaderSettings{ValidationType

      = ValidationType.Schema};

      settings.Schemas.Add(XmlSchema.Read(XmlReader.Create(xsdFile)));

      XmlReader reader = XmlReader.Create(xmlFile, settings);

      try

      {

      while(reader.Read());

      return true;

      }

      catch (XmlSchemaValidationException ex)

      {

      // indicates a validation error occurred.

      return false;

      }

      }

      This code loads XML into a XmlReader and a XML schema into a XMLSchemaSet. All attributes and elements in the XML document are validated when the document is read; there is no need to visit elements individually. If the XML document is not valid a XmlSchemaValidationException is thrown. The exception includes an error message, line number and position where the error occurred. Processing stops on the first error encountered.

      If you wish to process the entire document and see all errors, not just the first error, you can add an error handler for ValidationEventHandler event using the following code:

      settings.ValidationEventHandler += ValidationHandler;

      static void ValidationHandler(object sender,ValidationEventArgs e)

      {

      //process event here

      }

    XML Validation Using LINQ

    • 1

      Create a new C# project of the desired type in Visual Studio. If you want to add XML validation to an existing project, you can skip this step.

    • 2

      Open the "Add New Item" dialog box by clicking "Project" and then clicking "Add Class."

    • 3

      Specify a name for the new class that adheres to your coding standards and naming practices.

    • 4

      Right-click the project in the Solution Explorer to display the project menu.

    • 5

      Select "Add Reference" from the menu to display the "Add Reference" dialog box.

    • 6

      Select System.XML and System.Linq from the list of components and then click the "Select" button. Then, click "OK."

    • 7

      Add a method to the new class using the following code:

      private bool ValidateDocument(string xmlFile, string xsdFile)

      {

      // Create the XML document to validate against.

      XDocument xDoc = XDocument.Load(xmlFile, LoadOptions.PreserveWhitespace);

      XmlSchemaSet schema = new XmlSchemaSet();

      bool isError = new bool(); // Defaults to false.

      int countError = 1; // Counts the number of errors have generated.

      // Add the schema file you want to validate against.

      schema.Add(null, xsdFile);

      // Call validate and use a LAMBDA Expression as extended method!

      // Don't you love .NET 3.5 and LINQ...

      xDoc.Validate(schema, (sender, e) =>

      { switch (e.Severity)

      { case XmlSeverityType.Error:

      break;

      case XmlSeverityType.Warning:

      break;

      }

      countError++;

      isError = true; // If error fires, flag it to handle once call is complete.

      }

      , true); // True tells the validate call to populate the post-schema-validation

      // which you will need later, if you want to dive a littel deeper...

      return isError;

      }

      This code loads XML into a XDocument and a XML schema into a XMLSchemaSet. It then calls the Validate method on the XDocument using a lambda expression as the ValidationEventHandler.

  • No comments: