如何将以下嵌套XML加载到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>
我可以获得“项目”表格,但我如何获得子项目?
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);
}
答案 0 :(得分:2)
这对我有用,我所采取的唯一自由是更改子项目的字段名称。
subitem的原始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());
}
答案 1 :(得分:0)
使用数据集ReadXml。你必须在下面的链接上关注文章:
http://msdn.microsoft.com/en-us/library/7sfkwf9s(v=VS.100).aspx
For Instance:
DataSet ds = new DataSet();
ds.ReadXml(new StringReader(nestedXml));
StringBuilder sb = new StringBuilder();
ds.WriteXml(new StringWriter(sb));
Response.Write(sb.ToString());
当然,您可以使用ds.Tables[0]
和ds.Tables[1]
答案 2 :(得分:0)
String sss = @"<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>";
StringReader rr = new StringReader(sss);
DataSet sdread = new DataSet();
sdread.ReadXml(rr);