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;
}
持续学习、持续收获才能带来持续的满足和快乐!
浙公网安备 33010602011771号