如何获取DataSet.ReadXml以将DateTime属性解析为类型化DateTime

我有一个XML字符串,其中包含格式为“dd / MM / yyyy hh:mm:ss”的日期。

我正在使用DataSet.ReadXml()将此XML加载到数据集中。

如何确保此Date作为类型化DateTime存储在DataSet中,以便我可以相应地对其进行排序,格式化和RowFilter。

我的测试工具如下:

ASPX页面:

     Test   

代码背后:

 using System; using System.Data; using System.IO; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; namespace Test { public partial class XmlDateTypeList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { XDocument xDoc = new XDocument( new XElement("List", new XElement("Item", new XAttribute("Name", "A"), new XAttribute("Date", "21/01/2010 00:00:00") ), new XElement("Item", new XAttribute("Name", "B"), new XAttribute("Date", "12/01/2010 00:00:00") ), new XElement("Item", new XAttribute("Name", "C"), new XAttribute("Date", "10/01/2010 00:00:00") ), new XElement("Item", new XAttribute("Name", "D"), new XAttribute("Date", "28/01/2010 00:00:00") ) ) ); DataSet dataSet = new DataSet(); dataSet.ReadXml(new StringReader(xDoc.ToString())); GridView1.DataSource = dataSet.Tables[0]; GridView1.DataBind(); } } } 

这很痛苦,但根本问题是在这种情况下您的xml数据不能强类型,因为日期格式不是xs:date格式,并且一旦数据在数据集中就无法更改类型。 更复杂的是,.NET不会自动格式化“28/01/2010 00:00:00”作为日期。 因此,只需从一个数据表复制到另一个具有正确数据类型的数据表,然后重新格式化日期字符串。 这段代码有效,但远非优雅。 祝好运。

  using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; using System.Data; using System.IO; public partial class xmltest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { XDocument xDoc = new XDocument( new XElement("List", new XElement("Item", new XAttribute("Name", "A"), new XAttribute("Date", "21/01/2010 00:00:00") ), new XElement("Item", new XAttribute("Name", "B"), new XAttribute("Date", "12/01/2010 00:00:00") ), new XElement("Item", new XAttribute("Name", "C"), new XAttribute("Date", "10/01/2010 00:00:00") ), new XElement("Item", new XAttribute("Name", "D"), new XAttribute("Date", "28/01/2010 12:33:22") ) ) ); DataSet dataSet = new DataSet(); dataSet.ReadXml(new StringReader(xDoc.ToString())); DataSet dataSet2 = dataSet.Clone(); dataSet2.Tables[0].Columns[1].DataType = typeof(DateTime); // painful, painful copy over code from dataset1 to dataset2 foreach (DataRow r in dataSet.Tables[0].Rows) { DataRow newRow = dataSet2.Tables[0].NewRow(); newRow["name"] = r["name"]; newRow["Date"] = DateTime.ParseExact(r["Date"].ToString(), "dd/MM/yyyy HH:mm:ss", CultureInfo.CurrentCulture); dataSet2.Tables[0].Rows.Add(newRow); } GridView1.DataSource = dataSet2.Tables[0]; GridView1.DataBind(); } }