首页 > 代码库 > Linq实现对XML的简单增删查改

Linq实现对XML的简单增删查改

一、传统DOM创建XML方法

 private static void CreateXmlDocWithDom()        {            XmlDocument doc =new XmlDocument();            XmlElement inventory = doc.CreateElement("Inventory");            XmlElement car = doc.CreateElement("Car");            car.SetAttribute("ID", "1000");            XmlElement name = doc.CreateElement("PetName");            name.InnerText = "Jimbo";            XmlElement color = doc.CreateElement("Color");            color.InnerText = "Red";            XmlElement make = doc.CreateElement("Make");            make.InnerText = "Xuhang";            car.AppendChild(name);            car.AppendChild(color);            car.AppendChild(make);            inventory.AppendChild(car);            doc.AppendChild(inventory);            string savePath = @"E:\LinqToXML\Sample\InventoryWithDom.xml";            doc.Save(savePath);        }

二、用LinqToXML创建

精简模式:

  public static void CreateXmlDocWithLinqToXml()        {            XElement doc = new XElement("Inventory",                new XElement("Car", new XAttribute("ID", "1000"),                    new XElement("PetName", "Jimbo"),                    new XElement("Color", "green"),                    new XElement("Make", "Xuhang")));            string savePath = @"E:\LinqToXML\Sample\InventoryWithLinq.xml";            doc.Save(savePath);        }

完整模式(包含版本号,字符集以及样式表):

  public static void CreateFullXDocument()        {            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),                new XComment("Current Inventory of Cars"),                new XProcessingInstruction("xml-stylesheet", "href=http://www.mamicode.com/‘MyStyles.css‘ title=‘Compact‘ type=‘text/css‘"),                new XElement("Inventory",                    new XElement("Car", new XAttribute("ID", "1"),                        new XElement("PetName", "Jimbo"),                        new XElement("Color", "Green"),                        new XElement("Make", "Xuhang")),                    new XElement("Car", new XAttribute("ID", "2"),                        new XElement("PetName", "MeLvin"),                        new XElement("Color", "Red"),                        new XElement("Make", "Guizhu"))));            string savePath = @"E:\LinqToXML\Sample\FullInventory.xml";            doc.Save(savePath);        }

三、将数组或其它存储集合里的数据导入XML

 public static void MakeXElementFromArray()        {            var people = new[]            {                new {FristName="Mandy",age=32},                new {FristName="Andrew",age=40},                new {FristName="Dave",age=41},                new {FristName="Sara",age=31},            };            //XElement peopleDoc=new XElement("People",from c in people select new XElement("Person",new XAttribute("Age",c.age),            //    new XElement("FirstName",c.FristName)));            var m =people.Select(p => new XElement("Person", new XAttribute("Age", p.age), new XElement("FirstName", p.FristName)));                     XElement peopleDoc = new XElement("People", m);            Console.WriteLine(peopleDoc);        }

四、读取XML文件

  public static void ParseAndLoadExistingXml()        {            string myElement = @"<Car ID=‘2‘>                                    <PetName>MeLvin</PetName>                                    <Color>Red</Color>                                    <Make>Guizhu</Make>                                  </Car>";            XElement newElement = XElement.Parse(myElement);            Console.WriteLine(newElement);            Console.WriteLine();            XDocument myDocument = XDocument.Load(@"E:\LinqToXML\Sample\InsertInventory.xml");            Console.WriteLine(myDocument);        }

五、插入新的节点

 public static void InsertNewElement()        {            XDocument myDocument = XDocument.Load(@"E:\LinqToXML\Sample\InsertInventory.xml");            Random r=new Random();            XElement newElement = new XElement("Car", new XAttribute("ID",r.Next(100)),                                        new XElement("PetName", "Baoma"),                                        new XElement("Color", "yellow"),                                        new XElement("Make", "Mrxu"));            myDocument.Descendants("Inventory").First().Add(newElement);            string savePath = @"E:\LinqToXML\Sample\InsertInventory.xml";            myDocument.Save(savePath);        }

六、删除某组节点

 public static void DeleteNodeFromDoc()        {            XElement doc = new XElement("Inventory",                new XElement("Car", new XAttribute("ID", "1000"),                    new XElement("PetName", "Jimbo"),                    new XElement("Color", "green"),                    new XElement("Make", "Xuhang")));            doc.Descendants("PetName").Remove();            Console.WriteLine(doc);        }

七、查询某条记录

   public static void LookUpColorFromMake(string make)        {            XDocument myDocument = XDocument.Load(@"E:\LinqToXML\Sample\InsertInventory.xml");            var makefor = from car in myDocument.Descendants("Car")                          where (string)car.Element("Make") == make                          select car.Attribute("ID").Value;                         //select car.Element("Color").Value;            //var makefor = myDocument.Descendants("Car").Where(p => ((string)p.Element("Make")).Equals("Mrxu")).Select(p => p.Attribute("ID").Value);            string data =http://www.mamicode.com/ String.Empty;            foreach (var item in makefor)            {                data += String.Format("-{0}",item);            }            Console.WriteLine(data);        }

八、更新数据信息

public static void UpdateXmlDate()        {            XDocument myDocument = XDocument.Load(@"E:\LinqToXML\Sample\InsertInventory.xml");            var makefor = myDocument.Descendants("Car").Where(p => ((string) p.Element("Make")).Equals("Mrxu"));            foreach (var xElement in makefor)            {                xElement.Element("Make").Value = http://www.mamicode.com/"Xuhang";            }            Console.WriteLine(myDocument);        }

九、示例

  static void Main(string[] args)        {            //CreateXmlDocWithDom();            //CreateXmlDocWithLinqToXml();            //CreateFullXDocument();            //DeleteNodeFromDoc();            //InsertNewElement();            //ParseAndLoadExistingXml();            //MakeXElementFromArray();            //LookUpColorFromMake("Mrxu");            //UpdateXmlDate();            MakeXElementFromArray();            Console.ReadKey();        }

源码下载地址:链接:http://pan.baidu.com/s/1mg5MRJa 密码:lyn5

Linq实现对XML的简单增删查改