码迷,mamicode.com
首页 > 其他好文 > 详细

linq to xml 基本操作

时间:2014-12-15 23:28:02      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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 基本操作

标签:style   blog   io   ar   color   sp   for   on   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!