加上之前学习过Linq to Entity,因此学习起来也比较随心应手。
private string docName = string.Empty;//配置文件路径
#region ISystemModuleConfigService 成员
///
/// 添加
/// ///
///
///
public bool Add(string name, string controllerName)
{
XDocument xDoc = Load(docName);
if (IsExist(name))
{
xDoc.Element("configuration").Element("OPsystemConfig").Element("ChildSystems").Add(new XElement("ChildSystem",
new XElement("Name",name),
new XElement("ControllerName",controllerName)));
xDoc.Save(docName);
return true;
}
return false;
}
///
/// 修改
/// ///
///
///
public bool Modify(string name, string controllerName)
{
XDocument xDoc = Load(docName);
if (!IsExist(name))
{
var query = from Opsystem in xDoc.Descendants("ChildSystem")
where Opsystem.Element("Name").Value == name
select Opsystem;
foreach (XElement item in query)
{
item.Element("ControllerName").Value = controllerName;
}
xDoc.Save(docName);
return true;
}
return false;
}
///
/// 删除
/// ///
///
public bool Remove(string name)
{
XDocument xDoc = Load(docName);
if (!IsExist(name))
{
var query = from Opsystem in xDoc.Descendants("ChildSystem")
where Opsystem.Element("Name").Value == name
select Opsystem;
query.Remove();
xDoc.Save(docName);
return true;
}
return false;
}
///
/// 获得列表
/// ///
public IList
GetList()
{
XDocument xDoc = Load(docName);
List list = new List();
var query = from Opsystem in xDoc.Descendants("ChildSystem")
select new
{
Key = Opsystem.Element("Name").Value,
Value = Opsystem.Element("ControllerName").Value
};
foreach (var item in query)
{
SystemModuleConfig cOnfig= new SystemModuleConfig();
config.Name = item.Key;
config.COntrollerName= item.Value;
list.Add(config);
}
return list;
}
///
/// 获得一条ChildSystem数据
///
///
///
public SystemModuleConfig GetModel(string name)
{
XDocument xDoc = Load(docName);
SystemModuleConfig model = new SystemModuleConfig();
var query = from Opsystem in xDoc.Descendants("ChildSystem")
where Opsystem.Element("Name").Value == name
select new
{
Name = Opsystem.Element("Name").Value,
COntrollerName= Opsystem.Element("ControllerName").Value
};
foreach (var item in query)
{
model.Name = item.Name;
model.COntrollerName= item.ControllerName;
}
return model;
}
///
/// 加载Config文件
///
///
///
public XDocument Load(string path)
{
docName = path;
FileInfo file = new FileInfo(docName);
file.IsReadOnly= false;
return XDocument.Load(docName);
}
///
/// 验证Name=name的ChildSystem数据是否存在
///
///
///
private bool IsExist(string name)
{
XDocument xDoc = Load(docName);
var query = from Opsystem in xDoc.Descendants("ChildSystem")
where Opsystem.Element("Name").Value == name
select new
{
Name = Opsystem.Element("Name").Value
};
if (query.Count() == 0)
{
return true;
}
return false;
}