Linq to xml使用简单例子

首先保证你的frameworkd版本是3.0以上,导入一下包:

 

using System.Linq;
using System.Xml.Linq;
using System.Xml;

 


操作代码:

 

  //创建一个默认的配置文件
        public void creatConfigXml(String xmlPath) {
            XDocument doc = new XDocument(
                new XDeclaration("1.0","utf-8",null),
                new XElement("config",
                    new XElement("watch",
                        new XElement("type","2"),
                        new XElement("level","2")                        
                    )                      
                 )               
            );
            doc.Save(xmlPath);
        }


        //读取配置文件
        public WatcherConfig readConfigFromXml(String xmlPath) {
            WatcherConfig watcherConfig  = new WatcherConfig();

            XElement rootEle = XElement.Load(xmlPath);

            IEnumerable<XElement> queryResult = 
                                from ele in rootEle.Elements("watch")
                                select ele;
            XElement watchEle = queryResult.First();
            XElement typeEle = watchEle.Element("type");
            XElement levelEle = watchEle.Element("level");
            watcherConfig.Type = typeEle.Value.Trim();
            watcherConfig.Level = levelEle.Value.Trim();
            return watcherConfig;
        }


        // 更新配置
        public void updateConfigXml(WatcherConfig watcherConfig,String xmlPath)
        {
            XElement rootEle = XElement.Load(xmlPath);
            IEnumerable<XElement> queryResult =
                                    from ele in rootEle.Elements("watch")
                                    select ele;

            XElement watchEle = queryResult.First();
            watchEle.Element("type").Value = watcherConfig.Type.Trim();
            watchEle.Element("level").Value = watcherConfig.Level.Trim();
            rootEle.Save(xmlPath); 
        }

       //带条件的查询


        //读取xml信息
        public String readDtsxXmlConfig(String xmlPath, String configurationPath)
        {
           
            XElement rootEle = XElement.Load(xmlPath);
            XElement configuration =
                    (
                        from 
                             ele in rootEle.Elements("Configuration")
                        where 
                            ele.Attribute("Path").Value == configurationPath
                        select ele
                     ).Single() as XElement;




            return configuration.Element("ConfiguredValue").Value;


        }



 

 

posted on 2013-12-16 15:16  babyblue  阅读(127)  评论(0)    收藏  举报