C# System.Linq

之前一直不知道怎么将vs2008 开发的web 发布到net framework2.0 的iis中运行。今天终于知道 项目--右键--属性 可以实现framework 版本的转变。但是新的问题出现了。

在编译的过程中,use System.Linq 的应用报错。命名空间“System”中不存在类型或命名空间名称“Linq”(是否缺少程序集引用?)

如果是3.5版本的framework 添加System.data.Linq System.xml.linq ,System.xml,再不行还要添加System.Core(3.5)

Linq是.net fx3.5 版本以后才出现的。默认在fx2.0是不会有Linq的。所以会出现这种现象。

当用vs2008进行web开发时,将网站的dot net版本设为3.5时,相应的3.5类库并没有加载进来。就会出现缺少引用的问题。总之将fx3.5的相关类库加载进去即可。

当然如果项目中用不到Linq可以将dot net 版本设为2.0。避免不必要的错误。

System.Xml.Linq.dll 程序集定义了三个命名空间:System.Xml.Linq, System.Xml.Schema 和 System.Xml.XPath

最核心的是 System.Xml.Linq, 定义了对应 XML 文档个方面的很多类型

以前的 .NET XML编程模型需要使用很多冗长的 DOM API,而 LINQ to XML 则完全可以用与 DOM 无关的方式与 XML 文档交互。这样不但大大减少了代码行,而且这种编程模型可以直接映射到格式良好的XML文档结构。

1,在内存中创建xml文档

static void CreateFunctionalXmlDoc()

  {

  XDocument inventoryDoc =

  new XDocument(

  new XDeclaration("1.0", "utf-8", "yes"),

  new XComment("Current Inventory of AutoLot"),

  new XElement("Inventory",

  new XElement("Car", new XAttribute("ID", "1"),

  new XElement("Color", "Green"),

  new XElement("Make", "BMW"),

  new XElement("PetName", "Stan")

  ),

  new XElement("Car", new XAttribute("ID", "2"),

  new XElement("Color", "Pink"),

  new XElement("Make", "Yugo"),

  new XElement("PetName", "Melvin")

  )

  )

  );

  // Display the document and save to disk.

  Console.WriteLine(inventoryDoc);

  inventoryDoc.Save("SimpleInventory.xml");

  }

2,加载和解析xml

static void LoadExistingXml()

  {

  // Build an XElement from string.

  string myElement = @" Yellow Yugo ";

  XElement newElement = XElement.Parse(myElement);

  Console.WriteLine(newElement);

  Console.WriteLine();

  // Load the SimpleInventory.xml file.

  XDocument myDoc = XDocument.Load("SimpleInventory.xml");

  Console.WriteLine(myDoc);

  }