LINQ TO XML之判断不存在行则插入2010-12-14 博客园 陈希章近日写一个小工具,用到XML作为数据存储。其中要对两个XML文件进行匹配 比较。我现在使用的是LINQ TO XML语法,大致的例子如下if (File.Exists(cacheFile)) { XDocument cachedoc = XDocument.Load(cacheFile); var query = from p in cachedoc.Descendants ("file") where p.Attribute ("blogId").Value == SourceBlog select new { PostId = p.Attribute("postId").Value, PostName = p.Attribute ("name").Value.Replace(""","") }; //这一段是查询cacheFile的,将所有blogId等于某个blog的记录找出来
XDocument mappingdoc = XDocument.Load(mappingFile); foreach (var item in query) //循环之 { if (!mappingdoc.Descendants("mapping").Any ( m => m.Attribute("s").Value == “SourceBlog” && m.Attribute ("p").Value == item.PostId && m.Attribute ("t").Value == “Target”))//这里就是比较 CacheFile与MappingFile是否匹配 { mappingdoc.Element("mappings").Add ( new XElement("mapping", new XAttribute("s", “sourceBlog”), new XAttribute("p", item.PostId), new XAttribute("t", “Target”) )); } } mappingdoc.Save(mappingFile);代码比较简单,留为参考