Create XML document: xml element and properties : XML Create « XML « C# / C Sharp






Create XML document: xml element and properties

using System;
using System.Xml;

  class XMLDemo{
    [STAThread]
    static void Main(string[] args) {
      XmlDocument xmlDom = new XmlDocument();
      xmlDom.AppendChild(xmlDom.CreateElement("", "books", ""));
      XmlElement xmlRoot = xmlDom.DocumentElement;
      XmlElement xmlBook;
      XmlElement xmlTitle, xmlAuthor, xmlPrice;
      XmlText xmlText;
    
      xmlBook= xmlDom.CreateElement("", "A", "");
      xmlBook.SetAttribute("property", "", "a");
    
      xmlTitle = xmlDom.CreateElement("", "B", "");
      xmlText = xmlDom.CreateTextNode("text");
      xmlTitle.AppendChild(xmlText);
      xmlBook.AppendChild(xmlTitle);
            
      xmlRoot.AppendChild(xmlBook);
    
      xmlAuthor = xmlDom.CreateElement("", "C", "");
      xmlText = xmlDom.CreateTextNode("textg");
      xmlAuthor.AppendChild(xmlText);
      xmlBook.AppendChild(xmlAuthor);
            
      xmlPrice = xmlDom.CreateElement("", "D", "");
      xmlText = xmlDom.CreateTextNode("99999");
      xmlPrice.AppendChild(xmlText);
      xmlBook.AppendChild(xmlPrice);
    
      xmlRoot.AppendChild(xmlBook);
    
      Console.WriteLine(xmlDom.InnerXml);

      xmlDom.Save("books.xml");
      
      XmlDocument xmlDom2 = new XmlDocument();
      xmlDom2.Load("books.xml");
      Console.WriteLine(xmlDom2.InnerXml);

    }
  }


           
       








Related examples in the same category

1.Programmatically creating a new XML document.Programmatically creating a new XML document.
2.Append Child