Next step of programming

Just another WordPress.com weblog

Posts Tagged ‘XML

XML Serialization

without comments

Some time we need to save the data in the files which is nothing but the details of the object. For example i am having a application doing vector drawing and i want to save the details of the line object not the image file. How to save the line object and how to get it back. We can use serialization with which we can save our object in file directly and can load it too. Also we can use XML Serialization which is so popular these days.

We have to just mark out objects and class with certain Attributes like XMLRoot, XMLElement, XMLAttribute and so on.


using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace XMLSerialization
{
static class Program    
{
static void Main()
{
DoSerialization();
}

private static void DoSerialization()
{
Student student1 = new Student { Name = "A", Marks = 23 };
Student student2 = new Student { Name = "B", Marks = 25 };
Students students = new Students();

students.StudentList.Add(student1);
students.StudentList.Add(student2);

XmlSerializer xmlSerialize = new XmlSerializer(students.GetType());
StreamWriter writer = new StreamWriter("a.xml");
xmlSerialize.Serialize(writer, students);
writer.Close();

StreamReader reader = new StreamReader("a.xml");
Students studentsfromFile = (Students)xmlSerialize.Deserialize(reader);

foreach (Student st in studentsfromFile.StudentList)
{
Console.WriteLine("Name : {0} Marks : {1}", st.Name, st.Marks);
}

Console.ReadLine();
}
}

[XmlRoot("Students")]
public class Students    
{
[XmlElement("Student")]
public List<Student> StudentList = new List<Student>();
}

public class Student    
{
[XmlElement("Name")]
public string Name;
[XmlElement("Marks")]
public int Marks;
}
}

Written by A.Sethi

February 10, 2009 at 10:24 am

Getting sql query output in XML

without comments

Most of the time we will be executing sql queries and getting results as number of rows mainly records. In order to get those records in the XML format we can modify our existing query by adding just few keywords. In the result of those queries we will get the result in raw or formatted XML. 

Normal query 

Select * from customers

Result of select query

Result of select query

Query for getting result in XML format

Select * from customer FOR XML RAW or

Result of query with "for xml raw" keywords

Result of query with

Select * from custoemr FOR XML AUTO

Result of query "for xml auto" keywords

Result of query

Now we will get the result in well formed xml by getting the elements well tagged and root node as custoemr with following query

Select * from customer FOR XML AUTO, ELEMENTS, ROOT(‘customer’)

Result of Query "for xml auto, elements, root('customer')" keywords

Result of Query

Written by A.Sethi

September 3, 2008 at 11:20 am

Posted in MS SQL SERVER

Tagged with , , ,