简体   繁体   English

使用 XML 字符串加载数据表

[英]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.我有XMLDocument ,我使用xmlDocument.SelectSingleNode("./tag")将我想要的以下 xml 标签提取到一个字符串中,我想将它加载到 DataTable 中。

I tried using the dataTable.ReadXML();我尝试使用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.加载数据表的辅助方法,注意回退到 DataSet 的方法 ReadXml 而不是 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:如果您的 xml 以某种方式包含多个数据表,这并不总是合适的,因为此方法总是返回捕获中的第一个数据表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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