C# 比较两个 XML 文件并替换值
C# Compare two XML files and Replace Values
我有两个 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>
将 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"));
}
}
}
}
我有两个 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>
将 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"));
}
}
}
}