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" ?>
<people>
  <person firstname="john" lastname="doe">
    <contactdetails>
      <emailaddress>john@unknown.com</emailaddress>
      <phonenumber>9179799105</phonenumber>
    </contactdetails>
  </person>
  <person firstname="jane" lastname="doe">
    <contactdetails>
      <emailaddress>jane@unknown.com</emailaddress>
    </contactdetails>
  </person>
  <person firstname="pawel" lastname="chooch">
    <contactdetails>
      <emailaddress>pchooch@unknown.com</emailaddress>
    </contactdetails>
  </person>

</people>

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();
    doc.Load(@"..\..\data.xml");

    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
    person.Attributes.Append(firstNameAttribute);
    person.Attributes.Append(lastNameAttribute);

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

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

    doc.DocumentElement.AppendChild(person);
    Console.WriteLine("Modified xml...");
    doc.Save(Console.Out);
}


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.