I need to be able to add XML data to an already created parent node and place it under specific parent nodes.
Does anyone have any suggestions on the best way to do this?
I used the XMLWriter to create the original XML file.
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
for (int counter=0; counter<registeredEventCount; counter++)
{
try
{
XmlNode checkEvent = doc.SelectSingleNode("Event/Event[@id='" + registeredArrayList[counter] + "']");
if (checkEvent != null)
{
try
{
XmlNode checkDog = doc.SelectSingleNode("Event/Event[@id='" + registeredArrayList[counter] + "']/Dog[@id='" + ukcNumberArrayList[counter] + "']");
if (checkDog == null)
{
XmlElement newDogId = doc.CreateElement("Dog");
newDogId.SetAttribute("id", ukcNumberArrayList[counter].ToString());
XmlElement newDogName = doc.CreateElement("dogName");
newDogName.SetAttribute("id", dogNameArrayList[counter].ToString());
XmlElement newDogBreed = doc.CreateElement("breed");
newDogBreed.SetAttribute("id", breedArrayList[counter].ToString());
checkEvent.AppendChild(newDogId);
newDogId.AppendChild(newDogName);
newDogId.AppendChild(newDogBreed);
doc.Save(filePath);
}
else
{
MessageBox.Show("You have already registered this dog for this specific event");
}
}
EDIT: As code changed my old answer became invalid. Anyway I tested Your code in Visual Studio. It worked. Here is my input xml file:
and output:
My guess is that You have something wrong in Your XML file and code in ifs isn’t executed. I think XmlSerializer is better, and less error prone method for simple XML creating/updating.