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 in C#

1 Answer

0 votes
using System;
using System.Xml;
using System.Text; 

namespace Write_XML_File
{
	class Class1
	{
		static void Main(string[] args)
		{
			writeXML();
			readXML();
		}
		static void writeXML() 
		{ 
			XmlTextWriter writer = new XmlTextWriter(@"d:\test.xml", Encoding.UTF8); 

			writer.Formatting = Formatting.Indented; 
			writer.WriteStartDocument(true);  // true = standalone 
			writer.WriteStartElement("Humans"); 

			writer.WriteStartElement("Person"); 
			writer.WriteElementString("Name", "bob");                   
			writer.WriteElementString("Age", "43"); 
			writer.WriteEndElement(); 

			writer.WriteStartElement("Person"); 
			writer.WriteElementString("Name", "sam");                   
			writer.WriteElementString("Age", "38"); 
			writer.WriteEndElement(); 

			writer.WriteEndElement(); 
			writer.WriteEndDocument(); 
			writer.Close(); 
		}
		static void readXML() 
		{ 
			XmlTextReader reader = new XmlTextReader(@"d:\test.xml"); 

			while (reader.Read()) 
			{ 
				if(reader.Name.Equals("Name")) 
				{ 
					Console.WriteLine("Name : " + reader.ReadElementString("Name")); 
					Console.WriteLine("Age : " + reader.ReadElementString("Age")); 
				} 
			} 
		} 

	}
}
/* 
test.xml
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Humans>
  <Person>
    <Name>bob</Name>
    <Age>43</Age>
  </Person>
  <Person>
    <Name>sam</Name>
    <Age>38</Age>
  </Person>
</Humans>
*/





answered Aug 7, 2014 by avibootz

Related questions

1 answer 282 views
1 answer 210 views
1 answer 66 views
1 answer 130 views
1 answer 136 views
...