XML Classes

XmlReader

const string input = @"<?xml version='1.0' encoding='utf-8' ?>
<people>
	<person firstname='john' lastname='doe'>
		<contactdetails>
			<emailaddress>[email protected]</emailaddress>
		</contactdetails>
	</person>
	<person firstname='jane' lastname='doe'>
		<contactdetails>
			<emailaddress>[email protected]</emailaddress>
			<phonenumber>001122334455</phonenumber>
		</contactdetails>
	</person>
</people>";

using (var stringReader = new StringReader(input))
{
	using (var xmlReader = XmlReader.Create(stringReader, new XmlReaderSettings {IgnoreWhitespace = true}))
	{
		xmlReader.MoveToContent();
		xmlReader.ReadStartElement("People");
		var firstName = xmlReader.GetAttribute("firstName");
		var lastName = xmlReader.GetAttribute("lastName");

		xmlReader.ReadStartElement("Person");
		xmlReader.ReadStartElement("ContactDetails");
		var emailAddress = xmlReader.ReadString();
	}
}

XmlWriter

using (var stream = new StringWriter())
{
    using (var xmlWriter = XmlWriter.Create(stream, new XmlWriterSettings { Indent = true }))
    {
        xmlWriter.WriteStartDocument();
        xmlWriter.WriteStartElement("People");
        xmlWriter.WriteStartElement("Person");
        xmlWriter.WriteAttributeString("firstName", "John");
        xmlWriter.WriteAttributeString("lastName", "Doe");
        xmlWriter.WriteStartElement("ContactDetails");
        xmlWriter.WriteElementString("EmailAddress", "[email protected]");
        xmlWriter.WriteEndElement();
        xmlWriter.WriteEndElement();
        xmlWriter.Flush();
    }
    var output = stream.ToString();
}

XmlDocument

var doc = new XmlDocument();
doc.LoadXml(xml);
var nodes = doc.GetElementsByTagName("Person");
foreach (XmlNode node in nodes)
{
    var firstName = node.Attributes["firstName"].Value;
    var lastName = node.Attributes["lastName"].Value;
}

var newNode = doc.CreateNode(XmlNodeType.Element, "Person", "");
var firstNameAttribute = doc.CreateAttribute("firstName");
firstNameAttribute.Value = "Foo";
newNode.Attributes.Append(firstNameAttribute);

var lastNameAttribute = doc.CreateAttribute("lastName");
lastNameAttribute.Value = "Bar";
newNode.Attributes.Append(lastNameAttribute);

doc.DocumentElement.AppendChild(newNode);

doc.Validate(ValidationEventHandler);
doc.Save(Console.Out);

static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
	switch (e.Severity)
	{
		case XmlSeverityType.Error:
			Console.WriteLine("Error: {0}", e.Message);
			break;
		case XmlSeverityType.Warning:
			Console.WriteLine("Warning {0}", e.Message);
			break;
	}
}

XPathNavigator

var doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator iterator = nav.Select("//People/Person[@firstName='Jane']");
Console.WriteLine(iterator.Count); // Displays 1
while (iterator.MoveNext())
{
    string firstName = iterator.Current.GetAttribute("firstName", "");
    string lastName = iterator.Current.GetAttribute("lastName", "");
}