您的位置:首页 > 编程语言 > C#

C# Linq To XML的学习(创建并编辑XML树)示例

2009-03-23 17:48 585 查看
用Linq创建xml树,并对树中元素或属性的值修改。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml.Linq;

using System.Xml;

namespace LinqToXMLStudy

{

//***********************************************************************************************************

//Module:Program.cs

//Author:limeteor

//Create Date:2008-06-30

//***********************************************************************************************************

class Program

{

static void Main(string[] args)

{

//用linq创建XML树------------------------------------------------------------------------------------

XElement xmlTree = new XElement("Contacts",

new XElement("Contact",

new XElement("Name", "Patrick Hines"),

new XElement("Phone", "206-555-0144",

new XAttribute("Type", "Home")),

new XElement("Phone", "425-555-0145",

new XAttribute("Type", "Work")),

new XElement("Address",

new XElement("Street1", "123 Main St"),

new XElement("City", "Mercer Island"),

new XElement("State", "WA"),

new XElement("Postal", "68042")

)

)

);

Console.WriteLine(xmlTree);

//用linq创建XML树结束-------------------------------------------------------------------------------

//修改xml中属性的值---------------------------------------------------------------------------------

IEnumerable<System.Xml.Linq.XElement> xe = xmlTree.Descendants("Phone");//查询出元素名为Phone的所有集合,查询时区分大小写

var v = xe.Where(p => p.Attribute("Type").Value == "Home");

foreach (var s in v)

{

s.SetValue("hello");

}

Console.WriteLine("修改后的结果为:");

Console.WriteLine(xmlTree);

//修改xml中属性的值结束-----------------------------------------------------------------------------

Console.ReadKey();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: