在c#中将指定的子节点从一个xml文件复制到另一个xml文件
本文关键字:xml 文件 一个 另一个 复制 子节点 | 更新日期: 2023-09-27 18:09:09
下面是我的两个xml文件-示例xml文件
<tbltemp>
<Details>
<Id>1</Id>
<Name>John</Name>
<Date>25.09.2016</Date>
<Time>09:30:45</Time>
<Flag>1</Flag>
</Details>
<Details>
<Id>2</Id>
<Name>John</Name>
<Date>25.09.2016</Date>
<Time>01:30:45</Time>
<Flag>1</Flag>
</Details>
<Details>
<Id>3</Id>
<Name>John</Name>
<Date>25.09.2016</Date>
<Time>11:36:45</Time>
<Flag>1</Flag>
</Details>
<Details>
<Id>1</Id>
<Name>Jack</Name>
<Date>25.09.2016</Date>
<Time>11:36:45</Time>
<Flag>1</Flag>
</Details>
</tbltemp>
DBfile.xml
<tbltemp>
<Data>
<Id>1</Id>
<Name>John</Name>
<Age>23</Age>
<Team>Software</Team>
<Flag>1</Flag>
</Data>
<Data>
<Id>2</Id>
<Name>John</Name>
<Age>23</Age>
<Team>Software</Team>
<Flag>1</Flag>
</Data>
<Data>
<Id>3</Id>
<Name>John</Name>
<Age>23</Age>
<Team>Software</Team>
<Flag>1</Flag>
</Data>
<Data>
<Id>1</Id>
<Name>Jack</Name>
<Age>24</Age>
<Team>Software</Team>
<Flag>1</Flag>
</Data>
</tbltemp>
我想复制日期和时间在DBfile.xml文件从样本xml文件,其中id匹配两个xml文件。
我希望DBfile.xml像这样-
<tbltemp>
<Data>
<Id>1</Id>
<Name>John</Name>
<Age>23</Age>
<Team>Software</Team>
<Date>25.09.2016</Date>
<Time>09:30:45</Time>
<Flag>1</Flag>
</Data>
<Data>
<Id>2</Id>
<Name>John</Name>
<Age>23</Age>
<Team>Software</Team>
<Date>25.09.2016</Date>
<Time>01:30:45</Time>
<Flag>1</Flag>
</Data>
<Data>
<Id>3</Id>
<Name>John</Name>
<Age>23</Age>
<Team>Software</Team>
<Date>25.09.2016</Date>
<Time>11:36:45</Time>
<Flag>1</Flag>
</Data>
<Data>
<Id>1</Id>
<Name>Jack</Name>
<Age>24</Age>
<Team>Software</Team>
<Date>25.09.2016</Date>
<Time>11:36:45</Time>
<Flag>1</Flag>
</Data>
</tbltemp>
我一直在使用这样的代码
strDetails = "sample.xml";
strDBDir = "DBfile.xml";
var xDoc1 = XDocument.Load(strDetails);
var xDoc2 = XDocument.Load(strDBDir);
var doc1Entries = xDoc1.Descendants("Details");
/// var cloneEntries = doc1Entries.Select(x => new XElement(x));//"AgentId").Value == AgentId.ToString()
var cloneEntries = doc1Entries.Select(x => new XElement(x));
xDoc2.Descendants("Date").Last().AddFirst(cloneEntries);
xDoc2.Descendants("Time").Last().AddAfterSelf(cloneEntries);
xDoc2.Save(strDBDir);
但无法将数据从一个文件复制到另一个文件。,而是将loginid添加到DBfile.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
{
static void Main(string[] args)
{
XDocument sampleDoc = XDocument.Load(@"c:'temp'sample.xml");
XDocument dbDoc = XDocument.Load(@"c:'temp'dbfile.xml");
var merge =
(from db in dbDoc.Descendants("Data")
join sample in sampleDoc.Descendants("Details") on new { id = (int)db.Element("Id"), name = (string)db.Element("Name") } equals new { id = (int)sample.Element("Id"), name = (string)sample.Element("Name") }
select new { db = db, sample = sample });
foreach (var row in merge)
{
row.db.Add(new object[] {
row.sample.Element("Date"),
row.sample.Element("Time")
});
}
}
}
}