ozkank
ozkank

Reputation: 1462

Xml and Xml Schema

I want to show product's knowledges in xml format. i want to show productname whether another site, i don't want to show this. Thus, i want create base Xml schema file.in this way, i want to get different XML Schema from this XSD For every site. Can you help me?

Upvotes: 1

Views: 205

Answers (2)

Vincent Vancalbergh
Vincent Vancalbergh

Reputation: 3327

Regardless of what you want to do with the xml afterwards, the easiest way to make an xml out of your table is by serializing it:

  1. Make a C# class that is like your 10 columns (read up on Linq To Sql or Entity Framework for letting Visual Studio do the heavy lifting for you).

  2. Make your class XML Serializable. If you're making a "Plain Old C# Object" (sometimes called POCO), you don't need to do anything. In Linq to Sql set the Serialization Mode of the Datamodel to Unidirectional.

  3. Get your data in variables. With Linq To ... this is as simple as

var db = new MyRepository();
var myList = from r in db.MyTableRecords
             where r.someField == 'somevalue'
             select r;

Otherwise you're looking at getting your data yourself using an SqlConnection, SqlCommand and SqlDataReader:

var myList = new List<MyClass>();
using (var conn = new SqlConnection(MyConnectionString))
{
   conn.Open();
   using(var cmd = conn.CreateCommand())
   {
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = "SELECT ([Field1], ... [Field10]) FROM MyTable";
      using (var rdr = cmd.ExecuteReader())
      {
         while (rdr.Read())
         {
            myList.Add(new MyClass()
            {
               Field1 = rdr[0],
               ...
               Field10 = rdr[9]
            });
         }
      }
   }
}
  1. Serialize it:
StringBuilder sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
   XmlSerializer xs = new XmlSerializer(typeof(List<MyClass>));
   xs.Serialize(sw, myList);
}
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(sb.ToString());

Presto ! An XML Doc with your data. Using Linq to Sql this is quite quick and painless. After you grasp that and run into it's limitations try the Entity Framework and learn to generate your own classes using T4.

Upvotes: 3

Bonshington
Bonshington

Reputation: 4032

this is the easiest way

StringBuilder sb = new StringBuilder();
var xml = System.Xml.XmlWriter.Create(sb);

dataTable.WriteXml(xml, System.Data.XmlWriteMode.WriteSchema);

return sb.ToString();

Upvotes: 0

Related Questions