I am trying to generate XML in the following format:
<ImportSession>
<Batches>
<Batch>
<BatchFields>
<BatchField Name="Field1" Value="1" />
<BatchField Name="Field2" Value="2" />
<BatchField Name="Field3" Value="3" />
</BatchFields>
<Batch>
<Batches>
</ImportSession>
I have the following code:
XmlDocument doc = new XmlDocument();
XmlElement importSession = doc.CreateElement("ImportSession");
XmlElement batches = doc.CreateElement("Batches");
XmlElement batch = doc.CreateElement("Batch");
XmlElement batchFields = doc.CreateElement("BatchField");
doc.AppendChild(importSession);
XmlNode importSessionNode = doc.FirstChild;
importSessionNode.AppendChild(batches);
XmlNode batchesNode = importSessionNode.FirstChild;
batchesNode.AppendChild(batch);
XmlNode batchNode = batchesNode.FirstChild;
int numBatchFields = 9;
for (int j = 0; j < numBatchFields; j++)
{
batchNode.AppendChild(batchFields);
XmlElement batchfields = (XmlElement)batchNode.FirstChild;
batchfields.SetAttribute("Name", "BatchPrevSplit");
batchfields.SetAttribute("Value", j.ToString());
}
My problem is that It doesnt add the batchfield tags. It adds one so I get:
<ImportSession>
<Batches>
<Batch>
<BatchField Name="BatchPrevSplit" Value="8" />
</Batch>
</Batches>
</ImportSession>
It seems because I am trying to add the same Child element to the batchNode Node that it just overwrites the data in the existing tag. I tried putting in
XmlElement batchfields = (XmlElement)batchNode.ChildNodes.Item(j);
instead of
XmlElement batchfields = (XmlElement)batchNode.FirstChild;
but it doesnt append another Child to the batchNode if i use the same element so there is only 1 child. So can anyone tell me how I can achieve this?
XmlElement batchFields = doc.CreateElement("BatchField");shouldn't that be BatchFields? Looks like you are missing an element, this one is named wrong, and you need to add a BatchField element.