I want to add
some children to every occurrence of the group "Group" in an existing XML
file. I’m using an XmlNodeList and find
that the children are being added in the wrong place.
The XML
code I want to add is:
<Graphs>
<Graph1>
<Graph1Image />
<Graph1Title />
</Graph1>
<Graph2>
<Graph2Image />
<Graph2Title />
</Graph2>
<Graph3>
<Graph3Image />
<Graph3Title />
</Graph3>
<Graph4>
<Graph4Image />
<Graph4Title />
</Graph4>
</Graphs>
The test
file I’m using has two occurrences of the group "Group". Instead of getting the above inserted once
per Group, I’m getting this inserted in the second occurrence of Group:
<Graphs>
<Graph1>
<Graph1Image
/>
<Graph1Title />
<Graph1Image />
<Graph1Title />
</Graph1>
<Graph2>
<Graph2Image />
<Graph2Title />
<Graph2Image />
<Graph2Title />
</Graph2>
<Graph3>
<Graph3Image />
<Graph3Title />
<Graph3Image />
<Graph3Title />
</Graph3>
<Graph4>
<Graph4Image />
<Graph4Title />
<Graph4Image />
<Graph4Title />
</Graph4>
<Graph1 />
<Graph2 />
<Graph3 />
<Graph4 />
</Graphs>
The C# code is:
using System;
using
System.IO;
using
System.Xml;
public
class PRA
{
static void Main()
{
XmlDocument testDoc = new XmlDocument();
testDoc.Load("C:\\Users\\Paul_R_Anderson\\Desktop\\test.xml");
String groupString = "/SAN/EQLCollection/EQLArray/Groups/Group";
XmlElement graphsElement =
testDoc.CreateElement("Graphs");
XmlNodeList xnList =
testDoc.SelectNodes(groupString);
foreach
(XmlNode groupNode in xnList)
{
groupNode.AppendChild(graphsElement);
for (int j = 1; j < 5; j++)
{
String graphString =
String.Concat(groupString, "/Graphs");
String graphNumber = String.Concat("Graph", j);
XmlNode graphNode =
testDoc.SelectSingleNode(graphString);
XmlElement graphElement =
testDoc.CreateElement(graphNumber);
graphNode.AppendChild(graphElement);
String childString = String.Concat(groupString,
"/Graphs/", graphNumber);
XmlNode childNode =
testDoc.SelectSingleNode(childString);
String graphTitle =
String.Concat(graphNumber, "Title");
String graphImage = String.Concat(graphNumber,
"Image");
XmlElement titleElement =
testDoc.CreateElement(graphTitle);
XmlElement imageElement =
testDoc.CreateElement(graphImage);
childNode.AppendChild(imageElement);
childNode.AppendChild(titleElement);
}
}
testDoc.Save("C:\\Users\\Paul_R_Anderson\\Desktop\\testafter.xml");
}
}
I could sure use an idea about
where my code has gone awry!
Paul