Add XML Element to XmlDocument - CSharp System.Xml

CSharp examples for System.Xml:XML Document

Description

Add XML Element to XmlDocument

Demo Code


using System.Xml;
using System.Collections.Generic;
using System;/*from  w w  w.j ava2s.c om*/

public class Main{
        public static XmlDocument AddElement(XmlDocument xmlFile, string tagName, Dictionary<string, string> attributes) {
            XmlElement newElement = xmlFile.CreateElement(tagName);
            foreach (string key in attributes.Keys) {
                newElement.SetAttribute(key, attributes[key]);
            }
            xmlFile.DocumentElement.AppendChild(newElement);
            return xmlFile;
        }
        public static void AddElement(string xmlFilePath, string tagName, Dictionary<string, string> attributes) {
            XmlDocument xml = LoadXmlDocument(xmlFilePath);
            XmlElement newElement = xml.CreateElement(tagName);
            foreach (string key in attributes.Keys) {
                newElement.SetAttribute(key, attributes[key]);
            }
            xml.DocumentElement.AppendChild(newElement);
            xml.Save(xmlFilePath);
        }
}

Related Tutorials