Wednesday, February 25, 2009

Creating a XML document in .Net

Creating a XML document with C#
using System;
using System.Xml;

namespace AlokKumarSinha
{
class MainClass
{
XmlDocument xmldoc;
XmlNode xmlnode;
XmlElement xmlelem;
XmlElement xmlelem2;
XmlText xmltext;
static void Main(string[] args)
{
MainClass app=new MainClass();
}
public MainClass() //constructor
{
xmldoc=new XmlDocument();
//let's add the XML declaration section
xmlnode=xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"","");
xmldoc.AppendChild(xmlnode);
//let's add the root element
xmlelem=xmldoc.CreateElement("","root","");
xmltext=xmldoc.CreateTextNode("root text");
xmlelem.AppendChild(xmltext);
xmldoc.AppendChild(xmlelem);
//let's add another element (child of the root)
xmlelem2=xmldoc.CreateElement("","child1","");
xmltext=xmldoc.CreateTextNode("The text of the child1 element");
xmlelem2.AppendChild(xmltext);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);
//let's try to save the XML document in a file: C:\alok.xml
try
{
xmldoc.Save("c:\alok.xml"); //I've chosen the c:\ for the resulting file alok.xml
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}

Creating a XML document with VB.Net

Class MainClass
Private xmldoc As XmlDocument
Private xmlnode As XmlNode
Private xmlelem As XmlElement
Private xmlelem2 As XmlElement
Private xmltext As XmlText
Private Shared Sub Main(ByVal args As String())
Dim app As New MainClass()
End Sub
Public Sub New()
'constructor
xmldoc = New XmlDocument()
'let's add the XML declaration section
xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "")
xmldoc.AppendChild(xmlnode)
'let's add the root element
xmlelem = xmldoc.CreateElement("", "root", "")
xmltext = xmldoc.CreateTextNode("root text")
xmlelem.AppendChild(xmltext)
xmldoc.AppendChild(xmlelem)
'let's add another element (child of the root)
xmlelem2 = xmldoc.CreateElement("", "Child1", "")
xmltext = xmldoc.CreateTextNode("The text of child1")
xmlelem2.AppendChild(xmltext)
xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2)
'let's try to save the XML document in a file: C:\alok.xml
Try
xmldoc.Save("c:" & vbNullChar & "alok.xml")
'I've chosen the c:\ for the resulting file alok.xml
Catch e As Exception
Console.WriteLine(e.Message)
End Try
Console.ReadLine()
End Sub
End Class

No comments:

Post a Comment