Monday 22 May 2017

Xml Document

Now if efficiency isn't as big of a requirement or you know that the xml files you're going to be parsing are simple and short then the XmlDocument class may be the appropriate instrument. Again we start with an existing xml document

<?xml version="1.0" encoding="utf-8" ?>
  <person firstname="john" lastname="doe">
  <person firstname="jane" lastname="doe">
  <person firstname="pawel" lastname="chooch">


by loading it into and XmlDocument class we greatly simplify interacting with our xml data, we can query nodes and attributes easily we can even insert nodes and commit our changes

static void Main(string[] args)
    var doc = new XmlDocument();

    XmlNodeList nodes = doc.GetElementsByTagName("person");

    // Output the names of the people in the document
    foreach (XmlNode node in nodes) {
        string firstName = node.Attributes["firstname"].Value;
        string lastName = node.Attributes["lastname"].Value;
        Console.WriteLine("Name: {0} {1}", firstName, lastName);

    // Start creating a new node
    XmlNode person = doc.CreateNode(XmlNodeType.Element, "person", "");

    // give new node attribute
    XmlAttribute firstNameAttribute = doc.CreateAttribute("firstname");
    firstNameAttribute.Value = "Pawel";

    // give new node attribute
    XmlAttribute lastNameAttribute = doc.CreateAttribute("lastName");
    lastNameAttribute.Value = "Chooch";

    //give person node first and last name

    //give person sub node contact info
    XmlNode ContactInfo = doc.CreateNode(XmlNodeType.Element, "contactdetails", "");

    //give persons sub node cotact info a child node phonenumber
    XmlNode Phone = doc.CreateNode(XmlNodeType.Element, "phonenumber", "");
    Phone.InnerText = "5199912345";

    Console.WriteLine("Modified xml...");

now this relative simplicity comes at a performance hit, since we are loading all of the data into memory, modifying it and then writing it back to file this comes with significant overhead. for a small xml document the performance cost is trivial, but the larger and more complex the xml becomes the more visible the performance cost will be.