简体   繁体   English

使用Asp.net C#在DataSet中以4级嵌套读取xml数据

[英]Reading xml data in 4 level nesting in DataSet using Asp.net C#

I'm using XML to store data. 我正在使用XML来存储数据。 And have four level nesting as given below 并具有如下所示的四层嵌套

<?xml version="1.0" encoding="utf-8" ?>
<resrourceInfo>
    <month name="jan">
      <r>
         <rqstType></rqstType>
         <rsrceName></rsrceName>
         <dateRqstd></dateRqstd>
      </r>
      <r>
         <rqstType></rqstType>
         <rsrceName></rsrceName>
         <dateRqstd></dateRqstd>
      </r>
    </month>
    <month name="feb">
      <r>
         <rqstType></rqstType>
         <rsrceName></rsrceName>
         <dateRqstd></dateRqstd>
      </r>
      <r>
         <rqstType></rqstType>
         <rsrceName></rsrceName>
         <dateRqstd></dateRqstd>
      </r>
    </month>
</resourceInfo>

I want to treat this schema as 我想将此架构视为

  • All the months as Tables 所有月份如表
  • All the r as Rows 所有的行
  • All the tags inside r as Columns r内的所有标签为Columns

I've used C# as given below 我已经使用了C#,如下所示

DataSet ds = new DataSet();
ds.ReadXml(HttpContext.Current.Server.MapPath("~/DB.xml"));

But it's not working as expected. 但是它没有按预期工作。 Is there any other way I can do it ? 我还有其他方法可以做到吗? Thanks in Advance 提前致谢

The XML wasn't saved as a DataSet. XML未保存为数据集。 So you can do something like this 所以你可以做这样的事情

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using System.Data; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string input = "<?xml version=\\"1.0\\" encoding=\\"utf-8\\" ?>" + "<resrourceInfo>" + "<month name=\\"jan\\">" + "<r>" + "<rqstType>1</rqstType>" + "<rsrceName>2</rsrceName>" + "<dateRqstd>3</dateRqstd>" + "</r>" + "<r>" + "<rqstType>4</rqstType>" + "<rsrceName>5</rsrceName>" + "<dateRqstd>6</dateRqstd>" + "</r>" + "</month>" + "<month name=\\"feb\\">" + "<r>" + "<rqstType>7</rqstType>" + "<rsrceName>8</rsrceName>" + "<dateRqstd>9</dateRqstd>" + "</r>" + "<r>" + "<rqstType>10</rqstType>" + "<rsrceName>11</rsrceName>" + "<dateRqstd>12</dateRqstd>" + "</r>" + "</month>" + "</resrourceInfo>"; XDocument doc = XDocument.Parse(input); DataSet ds = new DataSet(); foreach (XElement month in doc.Descendants("month")) { DataTable dt = ds.Tables.Add(month.Attribute("name").Value); foreach (XElement row in month.Elements("r")) { if (dt.Rows.Count < 1) { foreach (XElement col in row.Elements()) { dt.Columns.Add(col.Name.ToString(), typeof(int)); } } DataRow newRow = dt.Rows.Add(); foreach (XElement col in row.Elements()) { newRow[col.Name.ToString()] = col.Value; } } } } } }​ 

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

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