您的位置:首页 > 其它

Linq To Xml 创建修改xml文档

2012-07-31 01:14 399 查看
static void Main(string[] args)
{
//创建xml文件
string path = @"E:\LinqToXmlTest.xml";
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Root",
new XElement("AccessCount",
new XAttribute("ClientId", 123),
new XAttribute("DateTime", DateTime.Now.ToString()))
));
xdoc.Save(path);

//读取xml文档
XElement root = XElement.Load(@"E:\LinqToXmlTest.xml");

//修改xml文档
var clientinfo = from h in root.Descendants("AccessCount")
where h.Attribute("ClientId").Value == "123"
select h;
var r = clientinfo.Single<XElement>();
r.ReplaceWith(new XElement("AccessCount",
new XAttribute("ClientId", 123456789),
new XAttribute("DateTime", DateTime.Now.ToString())));

//最后保存文件
root.Save(@"E:\LinqToXmlTest.xml");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: