日期:2014-05-20  浏览次数:21266 次

在XML文件中如何做類似SQL中的SUM()方法
Xml文件如下:
<?xml   version= "1.0 "   encoding= "utf-8 "   ?>
<Table_Payment>
    <payment   ID= "1 "   YEAR= "2006 "   MONTH= "12 "   DAY= "27 "   TypeID= "2 "   CONTENT= "買衣服 "   MONEY= "500.0000 "/>
    <payment   ID= "2 "   YEAR= "2006 "   MONTH= "12 "   DAY= "27 "   TypeID= "2 "   CONTENT= "買衣服 "   MONEY= "500.0000 "/>
</Table_Payment>
現在我想對[MONEY]進行類似于sql中的按年月Sum(),總不能實現,我采取的方法是先將xml文件讀入DataSet,然后使用DataTable的Compute方法來進行sum累總,搞了一個上午無法通過,求能者指教。
附上我的C#代碼:
int   intYear=2007;                        
int   intMonth=1;
DataSet     ds   =   new   DataSet();
ds.ReadXml(System.Windows.Forms.Application.StartupPath+   @ "\Payment.xml ");
object   ot   =   ds.Tables[0].Compute( "Sum(Convert(Double,[Money])) ",   "Year   = ' ' "+intYear+ " ' '   and   Month= ' ' "+intMonth+ " ' ' ");

------解决方案--------------------
try..

int intYear = 2006;
int intMonth = 12;
DataSet ds = new DataSet();
ds.ReadXml(@ "../../test.xml ");
DataColumn dc = new DataColumn( "total ");
dc.DataType = System.Type.GetType( "System.Decimal ");
dc.Expression = "Convert(MONEY, 'System.Decimal ') ";
ds.Tables[0].Columns.Add(dc);
object ot = ds.Tables[0].Compute( "Sum(total) ", "YEAR = ' " + intYear + " ' and MONTH= ' " + intMonth + " ' ");
Console.WriteLine(ot.ToString());