Append Child : XML Create « XML « C# / C Sharp






Append Child



using System;
using System.Xml;

class MainClass {
    public static void Main() {
        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 = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "1001";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);

        XmlNode nameNode = doc.CreateElement("productName");
        nameNode.AppendChild(doc.CreateTextNode("Coffee"));
        productNode.AppendChild(nameNode);
        XmlNode priceNode = doc.CreateElement("productPrice");
        priceNode.AppendChild(doc.CreateTextNode("0.99"));
        productNode.AppendChild(priceNode);

        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "1002";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        nameNode = doc.CreateElement("productName");
        nameNode.AppendChild(doc.CreateTextNode("Tea Pot"));
        productNode.AppendChild(nameNode);
        priceNode = doc.CreateElement("productPrice");
        priceNode.AppendChild(doc.CreateTextNode("12.99"));
        productNode.AppendChild(priceNode);

        doc.Save(Console.Out);
    }
}

           
       








Related examples in the same category

1.Programmatically creating a new XML document.Programmatically creating a new XML document.
2.Create XML document: xml element and properties