Khan
Khan

Reputation: 342

How to write an XML file by fetching values from Table in Database?

I need to add data to XML file.The data needs to be fetched from the Database Table using C#. Thanks in Advance

Upvotes: 0

Views: 821

Answers (3)

Sidharth Panwar
Sidharth Panwar

Reputation: 4654

Here are a few approaches:

Approach 1

  • Read data into a dataset using ADO.Net
  • Use dataset.WriteXml() (as suggested by Arshad)

Approach 2

  • Read data using SQLDataReader
  • Use XMLDocument to create a document
  • Use XMLWriter to write to the XML document
  • Save the XMLDocument

Approach 3

  • Read data using SQLDataReader
  • Use XDocument to create a document
  • Use XElement/XNode to write to the XML document
  • Save the XDocument

Let me know where you're facing issues with the approach.

Upvotes: 1

JJJCoder
JJJCoder

Reputation: 16946

If you need to enter specific information, XDocument / XElement are your friends (much easier than the old XmlDocument).

An example helper I use is:

public string ReplaceInXML(string xml, string nodeToUpdate, string newValue)
{
  // Load xml into a format we can do LINQ to XML on
  XElement root = XElement.Load((new StringReader(xml)), LoadOptions.None);

  // Look for all descendants where the node matches the one we want and update all the values to what we want
  // E.g. Get Node "productDetail" -> and set its value to newValue.
  root.Descendants().Where(i => i.Name.LocalName == nodeToUpdate)
    .ToList()
    .ForEach(i => i.ReplaceNodes(newValue));

  return root.ToString();
}

Upvotes: 1

Mohammad Arshad Alam
Mohammad Arshad Alam

Reputation: 9862

you can use DataSet.WriteXml() or DataTable.WriteXml():

YouDataSet.WriteXml(filepath)

Upvotes: 1

Related Questions