XML Classes
XmlReader
- You can move forward only through the file, and nothing is cached.
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
- A fast way to create an XML file. Just as with the
XmlReader
, it’s forward only and non-cached.
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
- It represents an in-memory XML document and uses a set of XmlNode objects to represent the various elements comprising the document.
- It supports navigating and editing a document.
XmlDocument
inherits from XmlNode
and adds specific capabilities for loading and saving documents.
XmlNode
helps you with reading content and attributes, and gives you methods for adding child nodes so that you can easily structure your document.
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
- It helps with navigating through an XML document to find specific information.
- One nifty feature for navigating through a document is
XPath
, a kind of query language for XML documents.
XmlDocument
implements IXPathNavigable
so you can retrieve an XPathNavigator
object from it.
- You can use methods similar to those in an
XmlDocument
to move from one node to another, or you can use an XPath
query.
- This enables you to select elements or attributes with certain values, similar to the way SQL selects data in a database.
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", "");
}