using System;
using System.Xml;
namespace Write_and_Read_XML_File_b
{
class Class1
{
static void Main(string[] args)
{
writeXML();
readXML();
}
public static void writeXML()
{
XmlDocument Doc = new XmlDocument();
XmlNode humanElement = Doc.CreateElement("Humans");
XmlNode personElement1 = Doc.CreateElement("Person");
XmlAttribute personElement1Name = Doc.CreateAttribute("Name");
personElement1Name.Value = "tom";
XmlAttribute personElement1Age = Doc.CreateAttribute("Age");
personElement1Age.Value = "37";
personElement1.Attributes.Append(personElement1Name);
personElement1.Attributes.Append(personElement1Age);
humanElement.AppendChild(personElement1);
XmlNode personElement2 = Doc.CreateElement("Person");
XmlAttribute personElement2Name = Doc.CreateAttribute("Name");
personElement2Name.Value = "sam";
XmlAttribute personElement2Age = Doc.CreateAttribute("Age");
personElement2Age.Value = "41";
personElement2.Attributes.Append(personElement2Name);
personElement2.Attributes.Append(personElement2Age);
humanElement.AppendChild( personElement2 );
Doc.AppendChild(humanElement);
Doc.Save("d:\\db.xml");
}
public static void readXML()
{
try
{
XmlDocument Doc = new XmlDocument();
Doc.Load("d:\\db.xml");
string text = "";
foreach(XmlNode node in Doc.DocumentElement.ChildNodes)
{
text="";
if (node.Name == "Person")
{
if (node.Attributes["Name"] != null)
text = node.Attributes["Name"].Value + "\r\n";
if (node.Attributes["Age"] != null)
text += node.Attributes["Age"].Value;
Console.WriteLine(text);
}
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
/*
output:
tom
37
sam
41
*/
/*
db.xml:
<Humans>
<Person Name="tom" Age="37" />
<Person Name="sam" Age="41" />
</Humans>
*/