Thursday, December 2, 2010

Writing XML Documents

Method 1:


In this sample example, I create a new file myxmlFile.xml using XmlTextWriter and use its various write methods to write XML items. 




OutPut of the above code looks like...
















==================================================


Method 2:



Using XmlDocument

The XmlDocument class represents an XML document. Load and LoadXml are two useful methods of this class. A Load method loads XML data from a string, stream, TextReader or XmlReader. LoadXml method loads XML document from a specified string. Another useful method of this class is Save. Using Save method you can write XML data to a string, stream, TextWriter or XmlWriter.




Output:

- <Student type="regular" Section="B">
  <Name>Tommy exName>

  Student>

==================================================

Method 3:

 how to load an XML document using XmlTextReader.

 In this sample example, we read books.xml file using XmlTextReader and call its Read method. After that we call XmlDocumetn's Load method to load XmlTextReader contents to XmlDocument and call Save method to save the document. 

using System.Xml;

namespace WriteXmlDocument
{
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();

//Load the the document with the last book node.
XmlTextReader reader = new XmlTextReader("c:\\books.xml");

reader.Read();

// load reader
doc.Load(reader);

// Display contents on the console
doc.Save("D:\\booksDuplicate.xml");
}
}
}
Output in booksDuplicate.xml looks like this...





















Method 4:


Writing Dataset data to an XML Document


using System.Xml;
using System.Data;
using System.Data.OleDb;
namespace ReadingXML2
{
    class Class1
    {
        static void Main(string[] args)
        {
            // create a connection
            OleDbConnection con = new OleDbConnection();
            con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";
            
      // create a data adapter
            OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con);
           
            // create a new dataset
            DataSet ds = new DataSet();

            // fill dataset
            da.Fill(ds, "Customers");

            // write dataset contents to an xml file by calling WriteXml method
            ds.WriteXml("C:\\OutputXML.xml");
        }
    }
}

Table inside the dataset in stored in OutputXML.xml file.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.