LINQ TO XML 示例

public void WriteToXML(FlightFileInfo flight)
        {
            try
            {
                lock (_obj)
                {
                    if (!Directory.Exists(logPath))
                    {
                        Directory.CreateDirectory(logPath);
                    }
                    string fileName = logPath + DateTime.Now.ToString("yyyyMMdd") + ".xml";
                    XElement root;
                    if (File.Exists(fileName))
                    {
                        root = XElement.Load(fileName);
                        //判断该条记录是否已经存在,如果不在,则新增,如果在,则更新
                        XElement ele = root.Elements("FlightFileInfo").Where(o => o.Attribute("FilePath").Value == flight.FilePath).FirstOrDefault();
                        if (ele != null)
                        {
                            ele.Attribute("ExecuteResult").SetValue(flight.ExecuteResult);
                            ele.Attribute("ExecuteCount").SetValue(flight.ExecuteCount);
                        }
                        else
                        {
                            XElement xele = root.Element("FlightFileInfo");
                            XElement element = new XElement("FlightFileInfo",
                                new XAttribute("FilePath", flight.FilePath),
                                new XAttribute("ExecuteResult", flight.ExecuteResult),
                                new XAttribute("ExecuteCount", flight.ExecuteCount)
                                );
                            xele.AddBeforeSelf(element);
                        }
                    }
                    else
                    {
                        root = new XElement("FlightInfos",
                        new XElement("FlightFileInfo",
                            new XAttribute("FilePath", flight.FilePath),
                            new XAttribute("ExecuteResult", flight.ExecuteResult),
                            new XAttribute("ExecuteCount", flight.ExecuteCount)
                            )
                       );
                    }
                    root.Save(fileName);
                }
            }
            catch (Exception ex)
            {

            }
        }

 

posted @ 2012-12-18 10:11  Gyoung  阅读(223)  评论(0编辑  收藏  举报