Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to read and write XML file with XmlDocument in C#

1 Answer

0 votes
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>
*/


answered Aug 8, 2014 by avibootz

Related questions

1 answer 299 views
299 views asked Aug 7, 2014 by avibootz
1 answer 210 views
1 answer 66 views
1 answer 130 views
...