C#比较两个XML文件并替换值

时间:2019-08-30 09:54:33

标签: c# xml compare edit

我有两个XML文件,我想用C#读取两个文件,并将值从旧的XML文件传输到新的XML文件。

我已经搜索了几个小时,但是找不到我的问题的解决方案,所以我希望这里的任何人都能帮助我。

//New File
<?xml version="1.0" encoding="utf-8"?>
<hmi-resources>
  <resource id="Plasma0">
    <value>Plasma 0</value>
  </resource>
  <resource id="Plasma1">
    <value>Plasma 1</value>
  </resource>
  <resource id="Plasma2">
    <value>Plasma 2</value>
  </resource>
  <resource id="Plasma3">
    <value>Plasma 3</value>
  </resource>
</hmi-resources>


//Old File
<?xml version="1.0" encoding="utf-8"?>
<hmi-resources>
  <resource id="Plasma0">
    <value>NEW Plasma 123</value>
  </resource>
  <resource id="Plasma1">
    <value>NEW Plasma abc</value>
  </resource>
</hmi-resources>

1 个答案:

答案 0 :(得分:0)

将Xml Linq与Join一起使用应该可以

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string OLD_FILENAME = @"c:\temp\test.xml";
        const string NEW_FILENAME = @"c:\temp\test2.xml";
        static void Main(string[] args)
        {
            XDocument oldDoc = XDocument.Load(OLD_FILENAME);
            XDocument newDoc = XDocument.Load(NEW_FILENAME);

            var query = (from o in oldDoc.Descendants("resource")
                        join n in newDoc.Descendants("resource") on (string)o.Attribute("id") equals (string)n.Attribute("id")
                        select new { o = o, n = n })
                       .ToList();

            foreach (var item in query)
            {
                item.n.Element("value").SetValue((string)item.o.Element("value"));
            }
        }
    }

}