Click here to Skip to main content
15,868,026 members
Articles / Programming Languages / C#
Tip/Trick

How to Save a DataRow to XML

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
2 Jul 2014CPOL1 min read 22K   260   6   5
Getting the XML data from a DataRow is surprisingly difficult. Here is one solution.

DataRowToXML snapshot

Introduction

Just recently, I had the need to save the contents of a DataRow as XML data for further processing. I looked at all the properties and methods that could be used, but nothing worked.

I couldn't find any really good solution for my problem in the different coding forums either, so I came up with my own solution.

Hopefully, it can help someone else.

Note: When running the demo, make sure to select a row in the Parent table by clicking on the row header.

Background

In this case, I have created a DataSet with DataTables named Parent, Child and GrandChild. The parent table is presented in three DataGridViews where a user can select one table and then convert that DataTable to XML.

Using the Code

I have an example DataSet that looks like this:

DataSet overview

Fill the dataset with some sample data.

C#
DataSetExample.ParentRow parent = null;
DataSetExample.ChildRow child = null;

parent = dataSetExample.Parent.AddParentRow("Object");
child = dataSetExample.Child.AddChildRow(parent, "XmlNode");
dataSetExample.GrandChild.AddGrandChildRow(child, "XmlLinkedNode");
dataSetExample.GrandChild.AddGrandChildRow(child, "XmlDocument");

child = dataSetExample.Child.AddChildRow(parent, "Encoding");
dataSetExample.GrandChild.AddGrandChildRow(child, "ASCIIEncoding");
dataSetExample.GrandChild.AddGrandChildRow(child, "UnicodeEncoding");
dataSetExample.GrandChild.AddGrandChildRow(child, "UTF32Encoding");

parent = dataSetExample.Parent.AddParentRow("XmlLinkedNode");
child = dataSetExample.Child.AddChildRow(parent, "XmlCharacterData");
dataSetExample.GrandChild.AddGrandChildRow(child, "XmlComment");

parent = dataSetExample.Parent.AddParentRow("LocalFileSettingsProvider");
child = dataSetExample.Child.AddChildRow(parent, "ClientSettingsProvider");
dataSetExample.GrandChild.AddGrandChildRow(child, "ProfileProvider");

The code below is inside a user triggered event.

In here, I want to get all XML data for a DataTable with a specific name. In this case, I want it as a string.

C#
private void buttonGetXML_Click(object sender, EventArgs e)
{
  // Only one row can be selected
  if (dgParents.SelectedRows.Count == 1)
  {
    DataGridViewRow dgv = dgParents.SelectedRows[0];
    DataRowView drv = (dgv.DataBoundItem as DataRowView);
    if (drv != null)
    {
      DataSetExample.ParentRow parentRow = (drv.Row as DataSetExample.ParentRow);
      if (parentRow != null)
      {
        string xmlData = "";
        // Write all data in the dataset to a string
        using (MemoryStream ms = new MemoryStream())
        {
          parentRow.Table.WriteXml(ms);
          byte[] data = ms.ToArray();
          xmlData = ASCIIEncoding.ASCII.GetString(data);
        }
        
        // Load the XML string into an XDocument
        XDocument xdoc = XDocument.Parse(xmlData);

        // Get the top node
        XName xnDataSet = XName.Get(parentRow.Table.DataSet.DataSetName, parentRow.Table.DataSet.Namespace);
        XElement xeDataSet = xdoc.Element(xnDataSet);

        // Find the Parent in the complete XML data that matches the attribute name.
        // E.g. ParentName = Object;
        XName xnParent = XName.Get("Parent", parentRow.Table.DataSet.Namespace);
        XName xnParentName = XName.Get("ParentName", parentRow.Table.DataSet.Namespace);
        XElement xeParent = xeDataSet.Elements(xnParent).
            Where(x => x.Element(xnParentName).Value == parentRow.ParentName).
            FirstOrDefault();

        // Now show the XML in a RichTextBox
        richTextBox.Text = xeParent.ToString();
      }
    }
  }
}

Points of Interest

I am not entirely happy with my solution. There should be an easier way.

Maybe someone else out there has done something in this area worth posting.

History

  1. First release
  2. Simplified the code and updated with a complete demo

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Philippines Philippines
I have worked with mobile phone testing in manufacturing for 20 years.
Originally from Sweden, but moved to China in 2012.
At the moment I am on a sabbatical year in the Philippines.

Over the years I have used various programming languages such as Pascal, C, C++, C#, SQL, XML, XSLT.

Comments and Discussions

 
QuestionHow to Save a DataRow to XML Pin
Victor Zhe21-May-15 9:58
Victor Zhe21-May-15 9:58 
AnswerRe: How to Save a DataRow to XML Pin
George Jonsson15-Jun-15 19:52
professionalGeorge Jonsson15-Jun-15 19:52 
GeneralRe: How to Save a DataRow to XML Pin
Victor Zhe16-Jun-15 0:08
Victor Zhe16-Jun-15 0:08 
To prevent XML damage by special chars {"&","<",">"} - modify last string in my code
C#
string result = String.Format(lsb.ToString(), Array.ConvertAll(lrow.ItemArray, x =>
           (x==null ? "" :
           x.ToString(). Replace("&", "&"+"amp;").Replace("<", "&"+"lt;").Replace(">", "&"+"gt;")));


modified 16-Jun-15 6:19am.

GeneralThoughts Pin
PIEBALDconsult2-Jul-14 3:20
mvePIEBALDconsult2-Jul-14 3:20 
GeneralRe: Thoughts Pin
George Jonsson2-Jul-14 3:58
professionalGeorge Jonsson2-Jul-14 3:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.