Quantcast
Channel: XML, System.Xml, MSXML and XmlLite forum
Viewing all articles
Browse latest Browse all 935

XML Serialization With Schema Providers In The .NET Framework - How to use this approach for application configuration settings?

$
0
0

Specifically I'm asking about this example  Enrich Your XML Serialization With Schema Providers In The .NET Framework

How do I read and write the XML configuration for Product from a file on disk? (not via a webservice)

namespace SchemaProviderExample 
{

    // Do not use this attribute: [XmlType("product_type", Namespace = "http://SchemaProviderExample.org/Product.xsd")]
    // You can not use the XmlType and the SchemaProvider attribute at the same time.  Only one is needed 
    // to specify the complex type that will represent the class in the generated schema.
    // Using the XmlRoot attribute to specify an element name that is declared in your schema provider 
    // will prevent the schema engine from using the class name which is the default.
    [XmlRoot(ElementName = "product_root", DataType = "product_type", 
        Namespace = "http://SchemaProviderExample.org/Product.xsd", IsNullable = false)]
	[XmlSchemaProviderAttribute("GetSchemaFile")]
	public class Product : IXmlSerializable
	{

        public override string ToString()
        {
            string s;
            s = "Product ID = " + productID + "\r\n";
            s += "Name = " + Name + "\r\n";
            s += "List Price = " + this.ListPrice + "\r\n";
            s += "Dealer Price = " + this.dealerPrice + "\r\n";
            return s;
        }

        /// <summary>
        /// You need a default public constructor if you want to serialize.
        /// </summary>
        public Product()
        {           
        }

        public Product(int ID, string name, decimal listPrice, decimal dealer)
        {
            // Set all data for this call.
            this.productID = ID;
            this.Name = name;
            this.ListPrice = listPrice;
            this.dealerPrice = dealer;
        }

        public Product(int p1, string p2, double p3, double p4)
        {
            // TODO: Complete member initialization
            this.p1 = p1;
            this.p2 = p2;
            this.p3 = p3;
            this.p4 = p4;
        }

		// public fields
		public string Name;
		public decimal ListPrice;
        // private fields
        private int productID;
        private decimal dealerPrice;
        private int p1;
        private string p2;
        private double p3;
        private double p4;

		//  public readonly property
		//  Note: since readonly fields can only be set in a constructor we need ProductID to
		//  be a property with only a getter and add a supporting private variable.
		public int ProductID
		{
			get { return productID; }
		}
		
		#region IXmlSerializable Members

		XmlSchema IXmlSerializable.GetSchema()
		{
            throw new System.NotImplementedException("The method or operation is not implemented.");
		}
		/// <summary>
		/// Elements must be read in the same order that they are written.
		/// You can see the importance of namespace in insuring that you are reading the correct elements.
		/// </summary>
		/// <param name="reader"></param>
		void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
		{
            string ns = "http://SchemaProviderExample.org/Product.xsd";

            // Do not specify a name when reading this element.  You do not know
            // what it will be.  It does not have to be "product_root".  For example,
            // if this class is used as a web method parameter then the first element will
            // be the parameter name.
            reader.ReadStartElement();

            productID = reader.ReadElementContentAsInt("product_id", ns);
			Name = reader.ReadElementString("name", ns);
            ListPrice = reader.ReadElementContentAsDecimal("list_price", ns);
            dealerPrice = reader.ReadElementContentAsDecimal("dealer_price", ns);
			reader.ReadEndElement();
		}

		/// <summary>
		/// Using this technique you can serialize private, protected and internal members.
		/// The root element is created for you automatically according to what is specified in the 
        /// XmlRoot attribute.  Therefore you do not need to do it yourself using WriteElementStart 
        /// and WriteElementEnd.
		/// </summary>
		/// <param name="writer"></param>
		void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
		{
			string ns = "http://SchemaProviderExample.org/Product.xsd";
			writer.WriteElementString("product_id", ns, ProductID.ToString());
			writer.WriteElementString("name", ns, Name.ToString());
			writer.WriteElementString("list_price", ns, ListPrice.ToString());
			writer.WriteElementString("dealer_price", ns, dealerPrice.ToString());
		}

		#endregion
		
        public static XmlSchemaComplexType GetSchemaFile(System.Xml.Schema.XmlSchemaSet xs)
		{
            // Read the file name from the configured settings.
            // See the BusinessEntitiesSettings.settings file for where this information is set.
            BusinessEntities.Properties.Settings settings = new BusinessEntities.Properties.Settings();
            string xsdFile = settings.ProductSchema;
            
            XmlSerializer schemaSerializer = new XmlSerializer(typeof(XmlSchema));
            XmlSchema schema = (XmlSchema)schemaSerializer.Deserialize(new XmlTextReader(xsdFile));
			xs.Add(schema);
            
            string tns = "http://SchemaProviderExample.org/Product.xsd";  // target namespace
            XmlQualifiedName name = new XmlQualifiedName("product_type", tns);
            XmlSchemaComplexType productType = (XmlSchemaComplexType) schema.SchemaTypes[name];

            // Use these lines for debuging the Schema provider.  This text will show up in the console window
            // after you issue the xsd.exe command.
            //Console.WriteLine("Name:  " + productType.Name);
            //Console.WriteLine("Schema File:  " + xsdFile);

            return productType;
		}
		
		/// <summary>
		/// The command below will create a schema from this class usingspcified schema provider:
		/// 
        /// 			xsd BusinessEntities.dll /type:SchemaProviderExample.Product						
		/// 
        /// This command will generate a C# class from a schema and put the class in the SchemaProviderExample namespace:
		/// 
        ///				xsd product.xsd /c /l:cd /n:SchemaProviderExample
		/// 
		/// 
		/// </summary>
		/// <param name="xs"></param>
		/// <returns></returns>
		public static XmlSchemaComplexType GetSchema(System.Xml.Schema.XmlSchemaSet xs)
		{
			// Namespaces need within this schema.
			string tns = "http://SchemaProviderExample.org/Product.xsd";  // target
			string xmlns = "http://www.w3.org/2001/XMLSchema";              // xml

			XmlSchema schema = new XmlSchema();
			//schema.Id = "product";
			schema.TargetNamespace = tns;
			//schema.Namespaces.Add("tns", tns);
			schema.ElementFormDefault = System.Xml.Schema.XmlSchemaForm.Qualified;

			XmlSchemaElement root = new XmlSchemaElement();
			root.Name = "product_root";
			root.SchemaTypeName = new XmlQualifiedName("product_type", tns);
			schema.Items.Add(root);

			XmlSchemaComplexType productType = new XmlSchemaComplexType();
			productType.Name = "product_type";
			schema.Items.Add(productType);

			XmlSchemaSequence sequence = new XmlSchemaSequence();
			productType.Particle = sequence;

			XmlSchemaElement productID = new XmlSchemaElement();
			productID.Name = "product_id";
			productID.SchemaTypeName = new XmlQualifiedName("int", xmlns);
			sequence.Items.Add(productID);

            // <xs:simpleType name="NameType">
            XmlSchemaSimpleType nameType = new XmlSchemaSimpleType();
            nameType.Name = "NameType";

            // <xs:restriction base="xs:string">
            XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
            restriction.BaseTypeName = new XmlQualifiedName("string", xmlns);

            // <xs:maxLength value="25"/>
            XmlSchemaMaxLengthFacet maxLength = new XmlSchemaMaxLengthFacet();
            maxLength.Value = "25";
            restriction.Facets.Add(maxLength);
            nameType.Content = restriction;
            schema.Items.Add(nameType);

            XmlSchemaElement name = new XmlSchemaElement();
            name.Name = "name";
            name.SchemaTypeName = new XmlQualifiedName("NameType",tns);
            sequence.Items.Add(name);

            XmlSchemaElement listPrice = new XmlSchemaElement();
			listPrice.Name = "list_price";
			listPrice.SchemaTypeName = new XmlQualifiedName("decimal", xmlns);
			sequence.Items.Add(listPrice);

			XmlSchemaElement dealerPrice = new XmlSchemaElement();
			dealerPrice.Name = "dealer_price";
			dealerPrice.SchemaTypeName = new XmlQualifiedName("decimal", xmlns);
			sequence.Items.Add(dealerPrice);
            // Add the newly created schema to the schema set.
			xs.Add(schema);

			// This is the type that is part of the schema just added to the schema set.  Notice that we are not returning the
			// root element.
			return productType;
		}

	}
}



Viewing all articles
Browse latest Browse all 935

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>