我有两个Xml文件
main.xml中
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table>
<RowNo>1</RowNo>
<BatchMId>632</BatchMId>
<RandomNo>513EHGPDX9GH</RandomNo>
<ParentRandomNo>0000003</ParentRandomNo>
<Status>6</Status>
<AggregrationTimestamp>08/06/2017 1:07:28 </AggregrationTimestamp>
<CommissioningTimestamp>06/06/2017 17:26:31</CommissioningTimestamp>
<Grade>A</Grade>
</Table>
<Table>
<RowNo>2</RowNo>
<BatchMId>632</BatchMId>
<RandomNo>6S91XPK1Y8AV</RandomNo>
<ParentRandomNo>0000004</ParentRandomNo>
<Status>6</Status>
<AggregrationTimestamp>08/06/2017 1:07:28 </AggregrationTimestamp>
<CommissioningTimestamp>06/06/2017 17:26:31</CommissioningTimestamp>
<Grade>A</Grade>
</Table>
</NewDataSet>
Change.xml
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table>
<RowNo>1</RowNo>
<BatchMId>632</BatchMId>
<RandomNo>513EHGPDX9GH</RandomNo>
<ParentRandomNo>0000003</ParentRandomNo>
<Status>5</Status>
<AggregrationTimestamp>09/06/2017 11:07:28 </AggregrationTimestamp>
<CommissioningTimestamp>09/06/2017 11:07:28</CommissioningTimestamp>
<Grade>B</Grade>
</Table>
</NewDataSet>
在两个文件中<randomno>
都是唯一的,两个文件都是相同的。 Change.xml只有一些更新的元素值。
现在我想用这些更改来更新Main.xml,并且需要这样的输出..
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table>
<RowNo>1</RowNo>
<BatchMId>632</BatchMId>
<RandomNo>513EHGPDX9GH</RandomNo>
<ParentRandomNo>0000003</ParentRandomNo>
<Status>5</Status>
<AggregrationTimestamp>09/06/2017 11:07:28 </AggregrationTimestamp>
<CommissioningTimestamp>09/06/2017 11:07:28</CommissioningTimestamp>
<Grade>B</Grade>
</Table>
<Table>
<RowNo>2</RowNo>
<BatchMId>632</BatchMId>
<RandomNo>6S91XPK1Y8AV</RandomNo>
<ParentRandomNo>0000004</ParentRandomNo>
<Status>6</Status>
<AggregrationTimestamp>08/06/2017 1:07:28 </AggregrationTimestamp>
<CommissioningTimestamp>06/06/2017 17:26:31</CommissioningTimestamp>
<Grade>A</Grade>
</Table>
</NewDataSet>
我在此文件中至少有500000条记录,我想在不使用c#中的任何循环的情况下更新此xml文件。如果有人对此有所了解,请告诉我。我尝试使用for循环,但更新它需要更多的时间。 所以,如果任何人有一个没有循环的想法,那么与我分享。
答案 0 :(得分:0)
请尝试以下获取字典:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication71
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Dictionary<string, XElement> dict = doc.Descendants("Table").GroupBy(x => (string)x.Element("RandomNo"), y => y).ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
}
答案 1 :(得分:0)
这是你的代码。工作完美。 Source是您的源集,更改位于更改集
DataSet changeSet = new DataSet();
changeSet.ReadXml("d:\\change.xml");
DataSet sourceSet = new DataSet();
sourceSet.ReadXml("d:\\source.xml");
sourceSet.Tables[0].PrimaryKey = new DataColumn[] { sourceSet.Tables[0].Columns["ParentRandomNo"] };
changeSet.Tables[0].PrimaryKey = new DataColumn[] { changeSet.Tables[0].Columns["ParentRandomNo"] };
try
{
sourceSet.Merge(changeSet, false);
sourceSet.AcceptChanges();
sourceSet.WriteXml("d:\\updated.xml");
}
catch (Exception)
{
throw;
}