【问题标题】:How to get DataType specific DataTable from XML如何从 XML 获取 DataType 特定的 DataTable
【发布时间】:2012-03-29 22:33:37
【问题描述】:

如何从 XML 中获取 DataType 特定的 DataTable

这是我的代码

string XMLReportFormat =@"<?xml version="1.0" encoding="utf-8" ?>
<Table>
    <ReportBody>
      <TableRow>
        <ID>1</ID>
        <ParentID>1</ParentID>
        <Key>First1</Key>
      </TableRow>
      <TableRow>
        <ID>4</ID>
        <ParentID>1</ParentID>
        <Key>FirstChild4</Key>
      </TableRow>
    </ReportBody>
</Table>";

StringReader sReader = new StringReader(XMLReportFormat);
DataSet ds = new DataSet();

if (sReader == null)
    return null;
ds.ReadXml(sReader);

在这里,我将所有DataType 列都设为String。 我想要一些像ID 和ParentID 这样的列作为Integer

【问题讨论】:

  • 您正在将此 xml 值设置为属性或其他内容?
  • @Vinicius:为什么财产会出现? ...我没有使用任何属性
  • 因为如果您使用的是属性,您可以尝试将 xml 属性(例如:ID)的值解析为具有相同名称的属性的类型,例如。

标签: c# xml datatable dataset type-conversion


【解决方案1】:

我发现的最简单的方法是确保您的 DataSet 读取 xml 架构。架构将为您的 DataSet 设置 XML 的数据类型。

DataSet.ReadXmlSchema

即:

DataSet ds = new DataSet();
ds.ReadXmlSchema(Server.MapPath("/YourSchema.xsd"));
ds.ReadXml(Server.MapPath("/YourXML.xml"));

我在 Microsoft Reports 中使用动态数据时遇到问题,因为来自 XML 的所有内容都是字符串。我尝试将项目复制到定义了数据类型的新数据集中,但这要容易得多。您可以让 c# 为任何 xml 文件编写一个默认架构,然后您可以根据需要进行编辑。

DataSet ds = new DataSet();
ds.ReadXml("Data.xml");
ds.WriteXmlSchema("Data.xsd");

我知道这篇文章很旧,但它帮助了我,所以我想我会分享我学到的东西。

【讨论】:

    【解决方案2】:

    抱歉试试这个 TryParse

    http://msdn.microsoft.com/en-us/library/f02979c7.aspx

      DataRow dr = ...;
      int number;
      bool result = Int32.TryParse(dr["column"], out number);
      if (result)
      {
         // is a number , you can use it        
      }
      else
      {
         // convert your data to String
      }
    

    【讨论】:

      【解决方案3】:

      是的!我找到了答案。

      private static DataTable CreateDataTable()
      {
          DataTable dt = new DataTable("TableRow");
          dt.Columns.Add(new DataColumn("ID", typeof(int)));
          dt.Columns.Add(new DataColumn("ParentID", typeof(int)));
          return dt;
      }
      public static DataTable GetReportFormatFromXML(string XMLReportFormat)
      {
          if (XMLReportFormat == string.Empty)
              return null;
          StringReader sReader = new StringReader(XMLReportFormat);
          DataSet ds = new DataSet();
      
          if (sReader == null)
              return null;
          ds.Tables.Add(CreateDataTable());
          return ds.Tables[0];
      }
      

      这条线对我有帮助:)

      ds.Tables.Add(CreateDataTable());
      

      【讨论】:

      • sReader 似乎没有在代码中的任何地方使用。
      猜你喜欢
      • 2012-03-28
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多