本文介绍了将嵌套 XML 加载到数据集中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下嵌套的 XML 加载到数据集中?

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

推荐答案

这对我有用,我唯一的自由是更改子项的字段名称.

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

子项的原始 XML

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

为子项修改 XML

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

这里是代码.

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

这篇关于将嵌套 XML 加载到数据集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 10:37