在silverlight中使用Linq TO XML
本DEMO演示了在silverlight 2(Beta1) 中使用Linq TO XML。流程是通过使用 WebClient 将XML以流的方式
抓到本地,然后再用XmlReader 进行读取.最终使用Linq To XML 将查询到的数据转成对象列表:)
本文中所使用的XML中的数据取自SQLSERVER自带的数据库NorthWind中的Customers表,通过使用如下SQL脚
本进行获取.
大家可以在SqlServer 2005 Management Studio 中单击"新建查询",选取系统自带的NorthWind数据库,
并在查询窗口下运行上面查询脚本,如下图所示:
将得到的XML内容保存到一个新建的XML文件中,名称为:Customer.xml, 并为其加上:
数据准备好了,将其看到项目中的ClientBin文件夹中.下面就开始写程序了:)
首先我们要先建立一个Silverlight Application, 名称为:XmlReader
然后将下面的Xaml内容拷则到Page.xaml中:
上面因为使用了DataGrid控件,所以在UserControl中多了一行代码进行名空间的解析,如下:
下面就是相应的CS代码了,首先我们需要定义一个CustomerInfo类在XmlReader项目中,其作用就是编写LINQ
TO XML 时进行数据转换和相应绑定,其代码如下:
紧跟着就是实现代码了,请看如下代码段(相关代码见注释):
最后还要包含下列空间的引用:
这样我们就可以编译运行一下代码,最终效果如下图:
好了,今天的内容就先到这里了:)
源码下载链接,请点击这里:)
抓到本地,然后再用XmlReader 进行读取.最终使用Linq To XML 将查询到的数据转成对象列表:)
本文中所使用的XML中的数据取自SQLSERVER自带的数据库NorthWind中的Customers表,通过使用如下SQL脚
本进行获取.
SELECT TOP 10 * FROM Customers FOR XML AUTO , ELEMENTS XSINIL
大家可以在SqlServer 2005 Management Studio 中单击"新建查询",选取系统自带的NorthWind数据库,
并在查询窗口下运行上面查询脚本,如下图所示:
将得到的XML内容保存到一个新建的XML文件中,名称为:Customer.xml, 并为其加上:
<?xml version="1.0"?>
<Table>
.//上面的XML内容
</Table>
<Table>
.//上面的XML内容
</Table>
数据准备好了,将其看到项目中的ClientBin文件夹中.下面就开始写程序了:)
首先我们要先建立一个Silverlight Application, 名称为:XmlReader
然后将下面的Xaml内容拷则到Page.xaml中:
<UserControl x:Class="XmlReader.Page" xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="800" Height="400" xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" >
<StackPanel Margin="10,10,10,10">
<my:DataGrid x:Name="CustomersGrid" Height="300" Margin="0,5,0,10"
RowBackground="LightSteelBlue" AlternatingRowBackground="AliceBlue" ><!--AutoGenerateColumns="True" -->
<my:DataGrid.Columns>
<my:DataGridTemplateColumn Header="CustomerID">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding CustomerID}" />
</StackPanel>
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTextBoxColumn
Header="ContactName"
Width="100"
DisplayMemberBinding="{Binding ContactName}"
FontSize="16" Visibility="Visible" >
<my:DataGridTextBoxColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
</Style>
</my:DataGridTextBoxColumn.ElementStyle>
<my:DataGridTextBoxColumn.EditingElementStyle>
<Style TargetType="TextBox">
<Setter Property="Foreground" Value="Blue"/>
</Style>
</my:DataGridTextBoxColumn.EditingElementStyle>
</my:DataGridTextBoxColumn>
<my:DataGridTemplateColumn Header="CompanyName">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding CompanyName}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTemplateColumn Header="Address">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Address}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTemplateColumn Header="City">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding City}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTemplateColumn Header="PostalCode">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding PostalCode}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridCheckBoxColumn
Header="Region?"
Width="75"
DisplayMemberBinding="{Binding Region}"
IsThreeState="True" />
</my:DataGrid.Columns>
</my:DataGrid>
<StackPanel>
<Button Click="OnClick" Grid.Row="1" Content="生成仅包含 CustomerID, CompanyName 的xml"></Button>
</StackPanel>
</StackPanel>
</UserControl>
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="800" Height="400" xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" >
<StackPanel Margin="10,10,10,10">
<my:DataGrid x:Name="CustomersGrid" Height="300" Margin="0,5,0,10"
RowBackground="LightSteelBlue" AlternatingRowBackground="AliceBlue" ><!--AutoGenerateColumns="True" -->
<my:DataGrid.Columns>
<my:DataGridTemplateColumn Header="CustomerID">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding CustomerID}" />
</StackPanel>
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTextBoxColumn
Header="ContactName"
Width="100"
DisplayMemberBinding="{Binding ContactName}"
FontSize="16" Visibility="Visible" >
<my:DataGridTextBoxColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
</Style>
</my:DataGridTextBoxColumn.ElementStyle>
<my:DataGridTextBoxColumn.EditingElementStyle>
<Style TargetType="TextBox">
<Setter Property="Foreground" Value="Blue"/>
</Style>
</my:DataGridTextBoxColumn.EditingElementStyle>
</my:DataGridTextBoxColumn>
<my:DataGridTemplateColumn Header="CompanyName">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding CompanyName}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTemplateColumn Header="Address">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Address}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTemplateColumn Header="City">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding City}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTemplateColumn Header="PostalCode">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding PostalCode}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridCheckBoxColumn
Header="Region?"
Width="75"
DisplayMemberBinding="{Binding Region}"
IsThreeState="True" />
</my:DataGrid.Columns>
</my:DataGrid>
<StackPanel>
<Button Click="OnClick" Grid.Row="1" Content="生成仅包含 CustomerID, CompanyName 的xml"></Button>
</StackPanel>
</StackPanel>
</UserControl>
上面因为使用了DataGrid控件,所以在UserControl中多了一行代码进行名空间的解析,如下:
xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
下面就是相应的CS代码了,首先我们需要定义一个CustomerInfo类在XmlReader项目中,其作用就是编写LINQ
TO XML 时进行数据转换和相应绑定,其代码如下:
/// <summary>
/// 客户类信息, 详情参见Customers.xml文件
/// </summary>
public class CustomerInfo
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public bool Region { get; set; }
}
/// 客户类信息, 详情参见Customers.xml文件
/// </summary>
public class CustomerInfo
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public bool Region { get; set; }
}
紧跟着就是实现代码了,请看如下代码段(相关代码见注释):
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
//WebClient读取指定路径下的XML文件
WebClient client = new WebClient();
client.OpenReadCompleted += OnReadComplated;
client.OpenReadAsync(new Uri("Customers.xml", UriKind.Relative));
}
//读取XML流中的相应内容后,将CustomerInfo类实例列表绑定到DataGrid控件
void OnReadComplated(object sender, OpenReadCompletedEventArgs e)
{
//获取信息
XElement xml = XElement.Load(System.Xml.XmlReader.Create(e.Result));
//定义查询方法
var query = from c in xml.DescendantsAndSelf("Customers")
select new CustomerInfo
{
CustomerID = c.Elements("CustomerID").SingleOrDefault().Value,
CompanyName = c.Elements("CompanyName").SingleOrDefault().Value,
ContactName = c.Elements("ContactName").SingleOrDefault().Value,
ContactTitle = c.Elements("ContactTitle").SingleOrDefault().Value,
Address = c.Elements("Address").SingleOrDefault().Value,
City = c.Elements("City").SingleOrDefault().Value,
PostalCode = c.Elements("PostalCode").SingleOrDefault().Value,
Country = c.Elements("Country").SingleOrDefault().Value,
Phone = c.Elements("Phone").SingleOrDefault().Value,
Fax = c.Elements("Fax").SingleOrDefault().Value,
Region = c.Elements("Region").SingleOrDefault().Value != "" ? true : false
};
//进行DataGrid控件数据项绑定
CustomersGrid.ItemsSource = query.ToList();
}
//输入仅包含CustomerID,CompanyName的XML内容
void OnClick(object sender, EventArgs args)
{
//获取DataGrid绑定的数据项信息
List<CustomerInfo> data = CustomersGrid.ItemsSource as List<CustomerInfo>;
//定义新的XML内容(结构)
XElement xml = new XElement("CustomerShortInfo",
from c in data
select new XElement("CustomerID",
new XAttribute("CustomerID", c.CustomerID),
new XAttribute("CompanyName", c.CompanyName)));
//使用下面的方法直接输出,该方法可用于UI界面调试,名空间引用自 System.Windows.Browser;
HtmlPage.Window.Alert(xml.ToString());
}
}
{
public Page()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
//WebClient读取指定路径下的XML文件
WebClient client = new WebClient();
client.OpenReadCompleted += OnReadComplated;
client.OpenReadAsync(new Uri("Customers.xml", UriKind.Relative));
}
//读取XML流中的相应内容后,将CustomerInfo类实例列表绑定到DataGrid控件
void OnReadComplated(object sender, OpenReadCompletedEventArgs e)
{
//获取信息
XElement xml = XElement.Load(System.Xml.XmlReader.Create(e.Result));
//定义查询方法
var query = from c in xml.DescendantsAndSelf("Customers")
select new CustomerInfo
{
CustomerID = c.Elements("CustomerID").SingleOrDefault().Value,
CompanyName = c.Elements("CompanyName").SingleOrDefault().Value,
ContactName = c.Elements("ContactName").SingleOrDefault().Value,
ContactTitle = c.Elements("ContactTitle").SingleOrDefault().Value,
Address = c.Elements("Address").SingleOrDefault().Value,
City = c.Elements("City").SingleOrDefault().Value,
PostalCode = c.Elements("PostalCode").SingleOrDefault().Value,
Country = c.Elements("Country").SingleOrDefault().Value,
Phone = c.Elements("Phone").SingleOrDefault().Value,
Fax = c.Elements("Fax").SingleOrDefault().Value,
Region = c.Elements("Region").SingleOrDefault().Value != "" ? true : false
};
//进行DataGrid控件数据项绑定
CustomersGrid.ItemsSource = query.ToList();
}
//输入仅包含CustomerID,CompanyName的XML内容
void OnClick(object sender, EventArgs args)
{
//获取DataGrid绑定的数据项信息
List<CustomerInfo> data = CustomersGrid.ItemsSource as List<CustomerInfo>;
//定义新的XML内容(结构)
XElement xml = new XElement("CustomerShortInfo",
from c in data
select new XElement("CustomerID",
new XAttribute("CustomerID", c.CustomerID),
new XAttribute("CompanyName", c.CompanyName)));
//使用下面的方法直接输出,该方法可用于UI界面调试,名空间引用自 System.Windows.Browser;
HtmlPage.Window.Alert(xml.ToString());
}
}
最后还要包含下列空间的引用:
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Windows.Browser;
using System.Xml.Linq;
using System.Net;
using System.Windows.Browser;
这样我们就可以编译运行一下代码,最终效果如下图:
好了,今天的内容就先到这里了:)
源码下载链接,请点击这里:)