I have some XML in a string
in memory exactly like this:
<symbols>
<symbol>EURCHF</symbol>
<symbol>EURGBP</symbol>
<symbol>EURJPY</symbol>
<symbol>EURUSD</symbol>
</symbols>
I want to read this into a DataTable
. I am doing it like this:
DataTable dt = new DataTable();
dt.TableName = "symbols";
dt.Columns.Add("symbol");
if (!String.IsNullOrEmpty(symbols))
{
dt.ReadXml(new StringReader(symbols));
}
However when I check the number of rows, the DataTable
ends up having zero rows. What am I doing wrong?
I've been searching for a easy way to do the same for some time too, but never really found what I actually wanted. Here's one solution I came across. It works, but I don't really like it as I first have to write the file into a DataSet
and then put the created DataSet
-Table into a DataTable
.
Anyway, here's the code:
DataSet ds = new DataSet();
ds.ReadXml(path);
DataTable newDataTable = ds.Tables[0];
I also tried .ReadXml
on my DataTable
but that always threw an Exception.
I'm not happy with this solution, but it at least works.
Another way:
public DataTable ReadXML(string yourPath)
{
DataTable table = new DataTable("Item");
try
{
DataSet lstNode = new DataSet();
lstNode.ReadXml(yourPath);
table = lstNode.Tables["Item"];
return table;
}
catch (Exception ex)
{
return table;
}
}
And here's XML format:
<?xml version="1.0" encoding="utf-8" ?>
<db>
<Item>
<Id>222</Id>
<OldCode>ZA</OldCode>
<NewCode>ZAF</NewCode>
<Name>Africa (South )</Name>
</Item>
</db>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With