VS2005.net 2.0 C #: Best way to generate xml file

What is the best way to generate xml file in .net 2.0 in terms of nodes etc. I don't think I can use LINQ. Any code sample or article would be helpful.

+2


source to share


2 answers


Your best bet is to use the XmlTextWriter class .

Here's a pretty basic example:

var writer = new XmlTextWriter("Foo.xml", Encoding.UTF8);
writer.WriteStartDocument();
writer.WriteStartElement("Foo");
writer.WriteAttributeString("hello", "world"); 
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();

      



This will give you:

<?xml version="1.0" encoding="utf-8"?>
<Foo hello="world" />

      

+4


source


Here's a piece of code that works:



XmlTextWriter myXW  = new XmlTextWriter(@"C:\NewXmlFile.xml", Encoding.UTF8)
myXW.WriteStartDocument();
myXW.WriteStartElement("Customers");
string strConn = myConnectionString;
OleDbConnection myConn = new OleDbConnection(strConn);
myConn.Open();
OleDbCommand myCMD = new OleDbCommand("select * from customers", myConn);
OleDbDataReader myRdr = myCMD.ExecuteReader();
while (myRdr.Read())
{
    myXW.WriteStartElement("Customer");
    myXW.WriteAttributeString("id", myRdr.GetString(0));
    myXW.WriteElementString("companyname", myRdr.GetString(1));
    myXW.WriteElementString("contactname", myRdr.GetString(2));
    myXW.WriteElementString("contactname", myRdr.GetString(3));
    myXW.WriteElementString("address", myRdr.GetString(4));
    myXW.WriteElementString("city", myRdr.GetString(5));
    myXW.WriteElementString("country", myRdr.GetString(8));
    myXW.WriteElementString("phone", myRdr.GetString(9));
    myXW.WriteElementString("fax", myRdr.GetString(10));
    myXW.WriteEndElement();
}
myXW.WriteEndElement();
myXW.WriteEndDocument();
myXW.Flush();
myXW.Close();

      

+1


source







All Articles