CSharp examples for XML:XML Document
Quickly Append Nodes in an XML Document
using System;//w ww . j ava 2 s . c om using System.Xml; public class GenerateXml { [STAThread] private static void Main(string[] args) { XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); XmlNode productsNode = doc.CreateElement("products"); doc.AppendChild(productsNode); XmlNode productNode = XmlHelper.AddElement("product", null, productsNode); XmlHelper.AddAttribute("id", "1001", productNode); XmlHelper.AddElement("productName", "Car", productNode); XmlHelper.AddElement("productPrice", "0.99", productNode); productNode = XmlHelper.AddElement("product", null, productsNode); XmlHelper.AddAttribute("id", "1002", productNode); XmlHelper.AddElement("productName", "test", productNode); XmlHelper.AddElement("productPrice", "102.99", productNode); doc.Save(Console.Out); Console.ReadLine(); } } public class XmlHelper { public static XmlNode AddElement(string tagName, string textContent, XmlNode parent) { XmlNode node = parent.OwnerDocument.CreateElement(tagName); parent.AppendChild(node); if (textContent != null) { XmlNode content = parent.OwnerDocument.CreateTextNode(textContent); node.AppendChild(content); } return node; } public static XmlNode AddAttribute(string attributeName, string textContent, XmlNode parent) { XmlAttribute attribute = parent.OwnerDocument.CreateAttribute(attributeName); attribute.Value = textContent; parent.Attributes.Append(attribute); return attribute; } }