Sunday, 27 January 2013

Writing xml file using XMLDocument c#

Writing xml file using XMLDocument c#

   Creating  an XML file using XMLDocument part of System.Xml namespace.
Step 1) Create Processing Instruction
Step 2) Create root element called "books" 
Step 3) Create book element
         Step 3.1) Create book title and add it to book
         Step 3.2) Create book price and add it to book
         Step 3.3) Create book publisher and add it to book
                  Step 3.3.1) Create a Authors Node
                  Step Create author node
                              Step Create firstname element  add it to author node
                               Step Create lastname element       add it to author node    
                   Step 3.3.2) add author node to Authors Node
                  Step   3.3.3)add authors node to book node
Step 4) Add book node to books node
Step 5) Save the XML document                 

    static void CreateXMLFile()
            XmlDocument doc = new XmlDocument();
            XmlProcessingInstruction xmlPI=
            doc.CreateProcessingInstruction("xml", "version='1.0'");
       XmlElement root=doc.CreateElement("books");
            XmlNode books = doc.AppendChild(root);
            XmlElement book=doc.CreateElement("book");
            //XmlAttribute idattribute =
            book.SetAttribute("id", "1");//doc.CreateAttribute("id");
            //idattribute.Value = "1";
            XmlElement title = doc.CreateElement("title"); title.InnerText = "C# Programming";
            XmlElement Price = doc.CreateElement("Price"); Price.InnerText = "$44.49";
            XmlElement Publisher = doc.CreateElement("Publisher"); Publisher.InnerText = "APRESS";

            XmlElement authors=doc.CreateElement("Authors");
            XmlElement author=doc.CreateElement("author");
            XmlElement firstname = doc.CreateElement("firstname"); firstname.InnerText = "jhon";
            XmlElement lastname = doc.CreateElement("lastname"); lastname.InnerText = "peter";
            author.AppendChild(firstname); author.AppendChild(lastname);





<?xml version='1.0'?>
  <book id="1">
    <title>C# Programming</title>

Tags: Writing xml file using XMLDocument c#,Writing an xml file using XMLDocument c#,Creating an XML file using C#, Create XML file using XMLDocument, Create an XML file using XMLDocument,System.Xml.XMLDocument,, Creating an XML in ASP.NET,Creating an XML in WPF. Creating an XML in Windows Forms.