Getting type information using xsd

serkan sendur 0 Tallied Votes 244 Views Share

To make some operations on XML elements you have to know their types. This snippet is about getting the types of these elements.

// this is default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Schema;
using System.Xml;
using System.Xml.XPath;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GetTypes();
    }
    private  void GetTypes()
    {
        XmlTextReader tr = new XmlTextReader(Server.MapPath("~/App_Data/XMLFile.xml"));
        XmlValidatingReader vr = new XmlValidatingReader(tr);

        vr.Schemas.Add(null,Server.MapPath("~/App_Data/XMLFile.xsd"));
        vr.ValidationType = ValidationType.Schema;
        vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

        while (vr.Read())
        {
            if (vr.NodeType == XmlNodeType.Element)
            {
                if (vr.SchemaType is XmlSchemaComplexType)
                {
                    XmlSchemaComplexType sct = (XmlSchemaComplexType)vr.SchemaType;
                    Response.Write("<div style='color:red'>" + vr.Name + " " + sct.Name + "</div>");
                }
                else
                {
                    object value = vr.ReadTypedValue();
                    try
                    {
                    Response.Write("<div style='color:blue'>" + vr.Name + " : " + value.GetType().Name + " " + value.ToString() + "</div>");
                    }
                    catch
                    {
                    }
                }
            }
        }
    }
    private  void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        Response.Write("***validation error</br>");
        Response.Write("Severity : " + args.Severity);
        Response.Write("Message : "+ args.Message);
    }
}
// this is default.aspx, it has basically nothing

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

// this is my xml file prototype
<?xml version="1.0" encoding="utf-8" ?>
<man>
  <length>180</length>
  <eyeColor>Green</eyeColor>
  <BOD>1981-08-10</BOD>
</man>

// this is my xsd file for my xml file
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="man">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="length" type="xs:int" />
        <xs:element name="eyeColor" type="xs:string" />
        <xs:element name="BOD" type="xs:boolean" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

// when you run the application the webpage displays the following 

man 
length : Int32 180
eyeColor : String Green
***validation error
Severity : ErrorMessage : The 'BOD' element has an invalid value according to its data type. 
it was able to get types from the xsd file and also validated the document against it.

Dani AI

Generated

's snippet is a useful demonstration of inspecting schema types while validating an XML document. Two practical clarifications for future readers: the validation error shown in the thread is caused by the XSD declaring BOD as xs:boolean while the XML contains a date string (1981-08-10), so the schema and data disagree. Also, the blank type name printed for the man element is expected when the element uses an anonymous complexTypeXmlSchemaComplexType.Name is null for anonymous types, so nothing is printed.

A minimal fix in the XSD is to declare BOD as a date (or dateTime if a time component is required):

<!-- change the BOD element to a date -->
<xs:element name="BOD" type="xs:date" />

xs:date expects the canonical form YYYY-MM-DD. To get a non-empty type name for man, declare a named complex type and reference it:

<xs:complexType name="ManType">
  <xs:sequence>
    <!-- length, eyeColor, BOD -->
  </xs:sequence>
</xs:complexType>

<xs:element name="man" type="ManType" />

For current .NET code prefer XmlReader + XmlReaderSettings (XmlValidatingReader is obsolete). The reader exposes schema info via reader.SchemaInfo.SchemaType; its TypeCode can be used to select typed read/parse logic. Example pattern:

var settings = new XmlReaderSettings();
settings.Schemas.Add(null, Server.MapPath("~/App_Data/XMLFile.xsd"));
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += ValidationCallBack;

using (var rdr = XmlReader.Create(Server.MapPath("~/App_Data/XMLFile.xml"), settings))
{
  while (rdr.Read())
  {
    if (rdr.NodeType != XmlNodeType.Element) continue;
    var schemaType = rdr.SchemaInfo?.SchemaType;
    if (schemaType == null) continue;

    switch (schemaType.TypeCode)
    {
      case XmlTypeCode.Int:
        int n = rdr.ReadElementContentAsInt();
        break;
      case XmlTypeCode.Date:
        DateTime dt = XmlConvert.ToDateTime(rdr.ReadElementContentAsString(), XmlDateTimeSerializationMode.Unspecified);
        break;
      default:
        string s = rdr.ReadElementContentAsString();
        break;
    }
  }
}

Additional tips: check SchemaInfo for null (no schema/no validation), prefer XmlSchemaSet and precompile schemas for performance, avoid writing directly from the validation handler to the response stream, and use TryParse/XmlConvert to handle format variations. As noted, the approach is practical once schema types match the XML.

deepalijain 0 Newbie Poster

good artical

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.