Click here to Skip to main content
Click here to Skip to main content

How to Save a DataRow to XML

, 2 Jul 2014
Rate this:
Please Sign up or sign in to vote.
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.

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.

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)

Share

About the Author

George Jonsson
Architect
China China
I have worked with mobile phone testing in manufacturing for 20 years.
Originally from Sweden, but moved to China in 2012.
Over the years I have used various programming languages such as Pascal, C, C++, C#, SQL, XML, XSLT.

Comments and Discussions

 
GeneralThoughts [modified] PinpremiumPIEBALDconsult2-Jul-14 3:20 
GeneralRe: Thoughts PinmemberGeorge Jonsson2-Jul-14 3:58 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 2 Jul 2014
Article Copyright 2014 by George Jonsson
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid