tags:

views:

1084

answers:

1

How do I load the following nested XML into a DataSet?

<items>
  <item>
   <id>i1</id>
   <name>item1</name>
   <subitems>
    <name>subitem1</name>
    <name>subitem2</name>
   </subitems>
  </item>
  <item>
   <id>i2</id>
   <name>item2</name>
   <subitems>
    <name>subitem1</name>
    <name>subitem2</name>
   </subitems>
  </item>
 </items>

I can get as far as a the "item" table but how do I get the subitems?

 MemoryStream itemsStream = new MemoryStream(Encoding.ASCII.GetBytes(itemsXML));
 DataSet itemsSet = new DataSet();
 itemsSet.ReadXml(itemsStream);
 foreach (DataRow itemRow in itemsSet.Tables["item"].Rows) {
     Console.WriteLine("column id=" + itemRow["id"] as string + " name=" + itemRow["name"] as string);
 }
+1  A: 

Hi,

This works for me, the only liberty I have taken is to Change the field name for the subitems.

Original XML for subitem

   <subitems>
     <name>subitem1</name>
     <name>subitem2</name>
   </subitems>

Modified XML for subitem

   <subitems>
       <name1>subitem1</name1>
       <name2>subitem2</name2>
   </subitems>

Here is the code.

        DataSet myDS = new DataSet();
        DataTable myTable = new DataTable("item");
        myTable.Columns.Add("id", typeof(string));
        myTable.Columns.Add("name", typeof(string));
        myTable.Columns.Add("name1", typeof(string));
        myTable.Columns.Add("name2", typeof(string));

        myDS.Tables.Add(myTable);

        string xmlData = "<items>  <item>   <id>i1</id>   <name>item1</name>   <subitems>    <name1>subitem1</name1>    <name2>subitem2</name2>   </subitems>  </item>  <item>   <id>i2</id>   <name>item2</name>   <subitems>    <name1>subitem3</name1>    <name2>subitem4</name2>   </subitems></item></items>";
        System.IO.MemoryStream itemsStream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(xmlData));

        myDS.ReadXml(itemsStream, XmlReadMode.IgnoreSchema);
        foreach (DataRow itemRow in myDS.Tables["item"].Rows)
        {
            MessageBox.Show("column id=" + itemRow["id"]  + " name=" + itemRow["name"]);
            MessageBox.Show(itemRow["name1"].ToString() + " - " + itemRow["name2"].ToString());
        }

HTH.

Best Regards Anand

Anand
Thanks for that, very close for what I'm after and I understand the mechanism now.
sipwiz