首页 > 代码库 > linq to xml 基本操作

linq to xml 基本操作

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml.Linq;namespace linqXML{    class Program    {        static void Main(string[] args)        {            XDocument doc = new XDocument();            XElement rt = new XElement("root");            doc.Add(rt);            XElement ele1 = new XElement("A",null, null);            ele1.SetAttributeValue("type", "CIN");            ele1.SetAttributeValue("from", "硬盘");            ele1.SetAttributeValue("ip", "188.1.1.31");            ele1.SetAttributeValue("active", "true");            rt.Add(ele1);            XElement ele2 = new XElement("B", null, null);            ele2.SetAttributeValue("type", "SC");                                                                                                                                                                                                                                                                                                                       ele2.SetAttributeValue("from", "FTP");            ele2.SetAttributeValue("ip", "188.1.1.32");            ele2.SetAttributeValue("active", "true");            rt.Add(ele2);            XElement ele3 = new XElement("C", null, null);            ele3.SetAttributeValue("type", "NC");            ele3.SetAttributeValue("from", "FTP");            ele3.SetAttributeValue("ip", "188.1.1.33");            ele3.SetAttributeValue("active", "false");            rt.Add(ele3);            string xmlfile=@"d:\tmp\test.xml";            doc.Save(xmlfile);            XElement rele = XElement.Load(xmlfile);            Console.WriteLine(rele);            Console.WriteLine("");            var xyz = from e in rele.Elements() select e;            foreach (XElement x in xyz)            {                Console.WriteLine("{0}: type={1}, from={2}, ip={3}, active={4}",                    x.Name,                     x.Attribute("type").Value,                    x.Attribute("from").Value,                    x.Attribute("ip").Value,                    x.Attribute("active").Value);            }            Console.WriteLine("");        }    }}

 

linq to xml 基本操作