Writing XML with the XmlDocument class



In the previous chapter, we wrote XML using the XmlWriter class. However, for some situations, especially when doing updates of existing XML, using the XmlDocument class can come in handy. You should be aware of the higher memory consumption though, mainly for large XML documents. Here is some code:

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

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

            XmlNode userNode = xmlDoc.CreateElement("qty");
            XmlAttribute attribute = xmlDoc.CreateAttribute("name");
            attribute.Value = "42";
            userNode.Attributes.Append(attribute);
            userNode.InnerText = "Product -11";
            rootNode.AppendChild(userNode);

            userNode = xmlDoc.CreateElement("qty");
            attribute = xmlDoc.CreateAttribute("name");
            attribute.Value = "39";
            userNode.Attributes.Append(attribute);
            userNode.InnerText = "Product -12";
            rootNode.AppendChild(userNode);

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

0 Comment's

Comment Form

Submit Comment