Reputation: 1507
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?
Upvotes: 0
Views: 69
Reputation: 115691
Rewrite your for
loop like this:
for (int j = 0; j < numBatchFields; j++)
{
XmlElement batchFields = doc.CreateElement("BatchField");
batchFields.SetAttribute("Name", "BatchPrevSplit");
batchFields.SetAttribute("Value", j.ToString());
batchNode.AppendChild(batchFields);
}
Upvotes: 3
Reputation: 22433
LINQ to XML will save you pain...
var xml = new XElement("ImportSession",
new XElement("Batches",
new XElement("Batch",
new XElement("BatchFields",
from j in Enumerable.Range(0,9)
select new XElement("BatchField",
new XAttribute("Name", string.Format("Field{0}", j)),
new XAttribute("Value", j)
)
)
)
)
);
Upvotes: 3