SpaceApple
SpaceApple

Reputation: 1327

Loading a DataTable with a XML string

I have the XMLDocument and I extract the following xml tags I want using the xmlDocument.SelectSingleNode("./tag") into a string and I want to load it inside a DataTable.

I tried using the dataTable.ReadXML(); but the overloads for this function do not allow a string argument.

Is there a better way of doing this?

Edit : Adding Code

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(string_With_Xml);
DataTable accessTable = new DataTable();
accessTable.ReadXml();

I Hope this adds more context to the question.

Upvotes: 0

Views: 5845

Answers (3)

Tore Aurstad
Tore Aurstad

Reputation: 3806

You can do the following approach, the byte array here can be loaded for a string using for example:

Encoding.UTF8.GetBytes(somestring)

Helper method to load the datatable, note fallback to DataSet's method ReadXml instead of Datatable ReadXml. This will not always be suitable in case your xml contains somehow several data tables, as this method always returns the first data table in the catch:

   public DataTable Convert(byte[] bytes)
    {
        var text = bytes.ToStringUtf8();
        if (string.IsNullOrWhiteSpace(text))
        {
            return null;
        }
        using (var stream = new MemoryStream(bytes))
        {
            try
            {
                var dt = new DataTable();
                dt.ReadXml(stream);
                return dt;
            }
            catch (InvalidOperationException ie)
            {
                Trace.WriteLine(ie);
                var ds = new DataSet();
                stream.Position = 0;
                ds.ReadXml(stream);
                if (ds.Tables.Count > 0)
                {
                    return ds.Tables[0];
                }
                return null;
            }
        }
    }

Upvotes: 0

Davecz
Davecz

Reputation: 1221

you can write extension like this:

public static someType ReadXml(this DataTable dt, string yourParam1, string yourParam2)
{
   method body....
}

Upvotes: 0

Habib
Habib

Reputation: 223227

You can try the following:

//Your xml
string TestSTring = @"<Contacts> 
                    <Node>
                        <ID>123</ID>
                        <Name>ABC</Name>
                    </Node>
                    <Node>
                        <ID>124</ID>
                        <Name>DEF</Name>
                    </Node>
            </Contacts>";
StringReader StringStream = new StringReader(TestSTring);
DataSet ds = new DataSet();
ds.ReadXml(StringStream);
DataTable dt = ds.Tables[0];

Upvotes: 4

Related Questions