Save, AppendChild, CreateXmlDeclaration, CreateElement : XmlDocument « XML « C# / C Sharp






Save, AppendChild, CreateXmlDeclaration, CreateElement

   
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 = "1";
        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 = "2";
        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.A Simple XML Example
2.LoadXml
3.Call GetElementsByTagName to get an element
4.Use Load method in XmlDocument to load xml document
5.Use SelectNodes to query nodes by XPath
6.Get XML Nodes in a Specific XML Namespace
7.Find Elements with an XPath Search
8.Add XmlElement
9.Load With Includes
10.Non CData Normalize