TOC

This article is currently in the process of being translated into Dutch (~52% done).

XML:

XML schrijven met de XmlDocument class

In het vorige hoofdstuk schreven we XML met de XmlWriter class. Voor sommige situaties echter, speciaal voor het updaten van bestaande XML, is het handig om de XmlDocument class te gebruiken. Let echter wel op de grotere geheugen consumptie, vooral bij grote XML documenten. Hier is wat code:

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace WritingXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode rootNode = xmlDoc.CreateElement("users");
            xmlDoc.AppendChild(rootNode);

            XmlNode userNode = xmlDoc.CreateElement("user");
            XmlAttribute attribute = xmlDoc.CreateAttribute("age");
            attribute.Value = "42";
            userNode.Attributes.Append(attribute);
            userNode.InnerText = "John Doe";
            rootNode.AppendChild(userNode);

            userNode = xmlDoc.CreateElement("user");
            attribute = xmlDoc.CreateAttribute("age");
            attribute.Value = "39";
            userNode.Attributes.Append(attribute);
            userNode.InnerText = "Jane Doe";
            rootNode.AppendChild(userNode);

            xmlDoc.Save("test-doc.xml");
        }
    }
}

En de resulterende XML:

<users>
  <user age="42">John Doe</user>
  <user age="39">Jane Doe</user>
</users>

Zoals je ziet is dit wat meer object georiënteerd dan de XmlWriter benadering, en vraat het ook wat meer code. wat je ziet is dat we een XmlDocument object maken, dat we gaan gebruiken om zowel nieuwe elementen als attributen de crëren, met behulp van de CreateElement() en CreateAttribute() methods. Elke keer als we dat doen, voegen we de elementen toe, ofwel direct aan het document, of aan een ander element. Je kunt dit zien in het voorbeeld waar het root element ("users") direct is toegevoegd aan het document, terwijl de user elementen zijn toegevoegd aan het root element. Attributes worden natuurlijk toegevoegd aan de elementen waar ze bij horen, gebruik makend van de Append() method bij de Attributes property. Het hele XML document wordt op de laatste regel naar de schijf toe geschreven, waarvoor we de Save() method gebruiken.

Now, as already mentioned, this requires a bit more code than when using the XmlWriter, but imagine a situation where you just need to go into an existing XML document and change a few values. Using the XmlWriter approach, you would have to first read all the information using an XmlReader, store it, change it, and then write the entire information back using the XmlWriter. Because the XmlDocument holds everything in memory for you, updating an existing XML file becomes a lot simpler. The following example opens the "test-doc.xml" file that we created in the previous chapter and increases every user's age by one. See how easy it is:

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace WritingXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("test-doc.xml");
            XmlNodeList userNodes = xmlDoc.SelectNodes("//users/user");
            foreach(XmlNode userNode in userNodes)
            {
                int age = int.Parse(userNode.Attributes["age"].Value);
                userNode.Attributes["age"].Value = (age + 1).ToString();
            }
            xmlDoc.Save("test-doc.xml");           
        }
    }
}

We load the XML file and ask for all the <user> nodes. We then iterate through them, read the age attribute into an integer variable, and then we write the value back to the node and attribute, after increasing the value by 1. At last, we save the document back to the same file and if you open it up, you will see that our users all just had a birthday. Pretty cool!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!