LINQ TO XML之判断不存在行则插入

近日写一个小工具,用到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);

代码比较简单,留为参考

本文由作者:陈希章 于 2009/6/19 7:15:58 发布在:http://www.cnblogs.com/chenxizhang/
本文版权归作者所有,可以转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
更多博客文章,以及作者对于博客引用方面的完整声明以及合作方面的政策,请参考以下站点:陈希章的博客中心
原文地址:https://www.cnblogs.com/chenxizhang/p/1506409.html