In this article I will show you how you can create an xml
document using C# in .Net. This article will also help you in your asp.net as
well as in your windows application which you create in .net.
In this article we will generate and show output in console
application. So here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace XML_Generation
{
class Program
{
//How to create a
Xml Document Programmatically Using C#.Net
static
void Main(string[]
args)
{
XmlDocument
doc = new XmlDocument();
XmlNode
docNode = doc.CreateXmlDeclaration("1.0",
"UTF-8", null);
doc.AppendChild(docNode);
XmlNode
productsNode = doc.CreateElement("Students");
doc.AppendChild(productsNode);
List<Student> _objstudent=new
List<Student>();
_objstudent = StudentData();
foreach(Student item in
_objstudent)
{
XmlNode
studentNode = doc.CreateElement("Student");
XmlAttribute
rollNoAttribute = doc.CreateAttribute("RollNo");
rollNoAttribute.Value =
item.RollNo.ToString();
studentNode.Attributes.Append(rollNoAttribute);
productsNode.AppendChild(studentNode);
XmlNode
nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode(item.Name));
studentNode.AppendChild(nameNode);
XmlNode
marksNode = doc.CreateElement("Marks");
marksNode.AppendChild(doc.CreateTextNode(item.Marks.ToString()));
studentNode.AppendChild(marksNode);
}
doc.Save(Console.Out);
Console.ReadLine();
}
//Data to
our list...
public
static List<Student> StudentData()
{
List<Student> _objStudent = new List<Student>();
_objStudent.Add(new Student {
Name = "Ram", RollNo = 1, Marks
= 85.5 });
_objStudent.Add(new Student {
Name = "vinay", RollNo = 1,
Marks = 85.5 });
return
_objStudent;
}
}
public class Student
{
public
string Name { get;
set; }
public
int RollNo { get;
set; }
public
double Marks { get;
set; }
}
}
|
In above code we have used Dotnet XMLdocumet class to
generarte the xml file at run time. In above code I have created a static
collection for populating data. You can use you database table data to pas it
and display the output.
0 comments:
Please let me know your view