简体   繁体   中英

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.

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];

you can write extension like this:

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

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;
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM