Generate XML Document with attributes : Xml Creation « XML « C# / CSharp Tutorial






using System;
using System.Xml;

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

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


      // Save the document (to the Console window rather than a file).
    doc.Save(Console.Out);
  }
}


  
  
    Pot
    102.99
  








30.1.Xml Creation
30.1.1.Create XML document by specifying the elements
30.1.2.Generate Xml Document
30.1.3.Generate XML Document with attributes
30.1.4.Helper method for generating the Xml document
30.1.5.Adding an element to the document