本文主要讨论如何在ActiveReports 7.0中使用RESTful Web Service所返回的XML数据。为了实现该功能,我们可以在LocateDataSource事件中通过DataSet或Object数据提供器实现运行时的数据绑定。当报表引擎需要加载数据时,会触发LocateDataSource事件。通过REST Web Service获取XML数据之后,我们可以在运行时使用DataSet数据提供器给报表绑定数据源。

 

实现,我们需要从一个URL中将XML数据加载到XmlDocument对象中,如何我们需要创建一个DataTable的实例,DataTable中的列名与XML中的节点名称对应。创建完成之后,我们可以遍历XmlDocument中的数据并填充中DataTable中,代码如下:

XmlDocument _doc = new XmlDocument();
dt = new DataTable();
dt.Columns.Add(new DataColumn("Title", typeof(String)));
dt.Columns.Add(new DataColumn("Artist", typeof(String)));
dt.Columns.Add(new DataColumn("Country", typeof(String)));
dt.Columns.Add(new DataColumn("Company", typeof(String)));
dt.Columns.Add(new DataColumn("Price", typeof(Double)));
dt.Columns.Add(new DataColumn("Year", typeof(Int32)));
_doc.Load("http://www.w3schools.com/xml/cd_catalog.xml");
XmlElement root = _doc.DocumentElement;
XPathNavigator navigator = _doc.CreateNavigator();
XPathNodeIterator cdData = navigator.Select("//CD");
while (cdData.MoveNext())
{
   XPathNodeIterator cdDataElements = cdData.Current.SelectChildren(XPathNodeType.Element);
   DataRow dr = dt.NewRow();
   while (cdDataElements.MoveNext())
    {
       //Read the values based on the element name
          switch (cdDataElements.Current.Name)
          {
               //convert values as necessary to match the business object's property types
               case "TITLE": dr["Title"] = cdDataElements.Current.Value.ToString();
                             break;
               case "ARTIST": dr["Artist"] = cdDataElements.Current.Value.ToString();
                              break;
               case "COUNTRY": dr["Country"] = cdDataElements.Current.Value.ToString();
                               break;
               case "COMPANY": dr["Company"] = cdDataElements.Current.Value.ToString();
                               break;
               case "PRICE": dr["Price"] = Convert.ToDouble(cdDataElements.Current.Value);
                             break;
               case "YEAR": dr["Year"] = Convert.ToInt32(cdDataElements.Current.Value);
                            break;
           }
      }
   dt.Rows.Add(dr);
}

如何在LocateDataSource事件中添加以下代码:

private void _runtime_LocateDataSource(object sender, LocateDataSourceEventArgs args)
{
  Object data = null;
  if (StringsAreEqual("DataSource1", args.DataSourceName))
  {
    if (StringsAreEqual("DataSet1", args.DataSetName))
    {
       data = dl.GetData;
    }
  }
}

 

运行截图:

 

源码下载: