首页 > 其他 > 详细

linq to xml 基本操作

时间:2014-12-15 23:27:17      阅读:414      评论:0      收藏:0      [点我收藏+]
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 基本操作

原文:http://www.cnblogs.com/xieqianli/p/4166024.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!