试了一下VB Orcas的新语法,觉得蛮强蛮好用的,特别是操纵数据XML方面,下面简单介绍一下
首先创建一个User实体类
Imports
Microsoft.VisualBasic
< Serializable() > _
Public Class User Class User
Public Name As String
Public Age As Integer
Sub New()Sub New(ByVal n As String, ByVal a As Integer)
Name = n
Age = a
End Sub
End Class
< Serializable() > _
Public Class User Class User
Public Name As String
Public Age As Integer
Sub New()Sub New(ByVal n As String, ByVal a As Integer)
Name = n
Age = a
End Sub
End Class
下面的代码涉及到两个命名空间,先把它们给引用过来
Imports
System.Xml.Linq
Imports System.Collections.Generic
Imports System.Collections.Generic
然后
'
定义根节点的名字
Dim root = " Users "
' 创建基于User的泛型列表
Dim Users As New List( Of User)
' 往里面添加数据
Users.Add( New User( " aaa " , 11 ))
Users.Add( New User( " bbb " , 22 ))
Users.Add( New User( " ccc " , 33 ))
' 定义XML文件的根节点
Dim UsersXml = << % = root % >></>
' 枚举列表中的项并添加到XML里面
For Each U As User In Users
UsersXml.Add( < User Name =< % = U.Name % > Age =< % = U.Age % >/> )
Next
' 保存为XML文件
UsersXml.Save(MapPath( " ~/App_Data/lishewen.xml " ))
Dim root = " Users "
' 创建基于User的泛型列表
Dim Users As New List( Of User)
' 往里面添加数据
Users.Add( New User( " aaa " , 11 ))
Users.Add( New User( " bbb " , 22 ))
Users.Add( New User( " ccc " , 33 ))
' 定义XML文件的根节点
Dim UsersXml = << % = root % >></>
' 枚举列表中的项并添加到XML里面
For Each U As User In Users
UsersXml.Add( < User Name =< % = U.Name % > Age =< % = U.Age % >/> )
Next
' 保存为XML文件
UsersXml.Save(MapPath( " ~/App_Data/lishewen.xml " ))
这段代码执行后会产生一个lishewen.xml文件,它里面的内容:
<?
xml version="1.0" encoding="utf-8"
?>
< Users >
< User Name ="aaa" Age ="11" />
< User Name ="bbb" Age ="22" />
< User Name ="ccc" Age ="33" />
</ Users >
< Users >
< User Name ="aaa" Age ="11" />
< User Name ="bbb" Age ="22" />
< User Name ="ccc" Age ="33" />
</ Users >
再下来,通过Linq语法把列表里Age>11的项筛选出来存为另一个XML文件
Dim
x
=
<<
%
=
root %
>><
%
=
From U
In
Users Where U.Age
>
11
Select
<
User Name
=<
%
=
U.Name %
>
Age
=<
%
=
U.Age %
>/>
%
></>
x.Save(MapPath( " ~/App_Data/lishewen1.xml " ))
x.Save(MapPath( " ~/App_Data/lishewen1.xml " ))
上面第一行的语法与SQL语句非常相像,只不过是把Select放后面了,它产生的XML文件的内容:
<?
xml version="1.0" encoding="utf-8"
?>
< Users >
< User Name ="bbb" Age ="22" />
< User Name ="ccc" Age ="33" />
</ Users >
< Users >
< User Name ="bbb" Age ="22" />
< User Name ="ccc" Age ="33" />
</ Users >
Linq的语法的确很Cool,想想以前用实现这种效果只能通过For Each+IF来实现,现在只要一两行代码就搞定了