【发布时间】:2020-05-20 15:11:27
【问题描述】:
我收到一个基本 XML 文件,我需要创建 N 个具有不同内容值的 XmlFiles。基本上我会 一个副本,更改一些节点值并创建新文件而不修改基础文件。
我将每个 XML 文档添加到文档列表中以执行其他过程,然后进行交互并创建 N 个文件。 在我的代码执行之后,我最终得到了所有具有相同信息的文件,即使是基础文件也被修改了。 我创建了一个基本代码来演示它。感谢您解释为什么会发生这种情况。
// file1.xml
<?xml version="1.0" encoding="UTF-16"?>
<BOM>
<BO>
<AdmInfo>
<Object>2</Object>
<Version>2</Version>
</AdmInfo>
<BusinessPartners>
<row>
<CardCode>111111</CardCode>
<CardName>MADERAS DE AGUADULCE, S.A</CardName>
<GroupCode>P-Locales</GroupCode>
</row>
</BusinessPartners>
</BO>
</BOM>
// C# code - method that change the value into the xmlFile.
public XmlDocument ChangeValues(XmlDocument document, List<Tuple<string, string>> AtriValues )
{
XmlDocument NewXMLDocument = new XmlDocument();
// pass the content to another XmlDocument
NewXMLDocument = document;
foreach (var Atribute in AtriValues)
{
XmlElement root = NewXMLDocument.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName(Atribute.Item1.ToString());
IEnumerator ienum = elemList.GetEnumerator();
while (ienum.MoveNext())
{
XmlNode title = (XmlNode)ienum.Current;
// Console.WriteLine(title.InnerText);
title.InnerText = Atribute.Item2.ToString();
//xn[Atribute.Item1.ToString()].InnerText = Atribute.Item2.ToString();
}
}
return NewXMLDocument;
}
// C# code- the main prg
static void Main(string[] args)
{
Util2 Util = new Util2();
List<XmlDocument> Documents = new List<XmlDocument>();
XmlDocument xmlDocument = new XmlDocument();
// load the XML file
xmlDocument.Load(@"C:\WIP\BaSe\TEST\file1.xml");
// Save the base file
Documents.Add(xmlDocument);
// Change the content of the document to create document A
List<Tuple<string, string>> AtriValuesA = new List<Tuple<string, string>>();
AtriValuesA.Add(new Tuple<string, string>("CardCode", "9999"));
AtriValuesA.Add(new Tuple<string, string>("GroupCode", "AA"));
Documents.Add(Util.ChangeValues(xmlDocument, AtriValuesA));
// Change the content of the document to create document B
List<Tuple<string, string>> AtriValuesB = new List<Tuple<string, string>>();
AtriValuesB.Add(new Tuple<string, string>("CardCode", "2222"));
AtriValuesB.Add(new Tuple<string, string>("GroupCode", "BB"));
Documents.Add(Util.ChangeValues(xmlDocument, AtriValuesB));
// get the document and then save then
Documents[0].Save(@"C:\WIP\BaSe\TEST\base.xml");
Documents[1].Save(@"C:\WIP\BaSe\TEST\DOCA.xml");
Documents[2].Save(@"C:\WIP\BaSe\TEST\DOCB.xml");
}
【问题讨论】:
标签: c# xmldocument