I am trying to do add a repeating XmlNode into and existing XML document and
have had some problems.
The base XML:
<Property>
<Premises>
<Endorsement>
<ShortWording/>
<Wording/>
</Endorsement>
<Address>
<Line1>41 Acacia Avenue</Line1>
<Line2>Town</Line2>
<Line3>City</Line3>
<Postcode>XX9 9 9XX</Postcode>
</Address>
</Premises>
</Property>
I am trying to add two new endorsements, as follows:
<Endorsement>
<ShortWording>s a</ShortWording>
<Wording>wa</Wording>
</Endorsement>
<Endorsement>
<ShortWording>s b</ShortWording>
<Wording>wb</Wording>
</Endorsement>
So initially I tried the following code:
XmlDocument doc = new XmlDocument();
doc.Load("in.xm l"); //Contains the base XML shown above
string insertionPoint = "/*/Premises/Endorsement[1]";
XmlNode childNode = doc.SelectSingl eNode(insertion Point);
XmlElement endorsements = doc.CreateEleme nt("e");
endorsements.In nerXml =
"<Endorsement>< ShortWording>sa </ShortWording><W ording>wa</Wording></Endorsement><En dorsement><Shor tWording>sb</ShortWording><W ording>wb</Wording></Endorsement>";
foreach(XmlNode insertNode in endorsements.Ch ildNodes)
{
doc.SelectSingl eNode(insertion Point).ParentNo de.InsertAfter( insertNode,
childNode);
}
On the first iteration through the foreach loop the insertNode correctly
contains the first ChildNode of the endorsements XMlElement. However on the
second iteration the insertNode contains the <Address> element from the
original document. Why has this suddenly switched to the base XmlDocument?
Where has my second child node in the endorsements variable gone?
So instead I tried to tackle the loop processing as follows:
XmlNodeList nl = endorsements.Ch ildNodes;
for (int count = 0; count <= nl.Count; count++)
{
XmlNode insertNode = nl.Item(count);
doc.SelectSingl eNode(insertion Point).ParentNo de.InsertAfter( insertNode,
childNode);
}
Again, on the first iteration (count = 0) everything is fine. However on
the second iteration (count = 1) the insertNode is a null object as the
XmlNodeList nl now only contains a single item.
Finally I tried changing the statement that initialises the insertNode as
follows:
XmlNode insertNode = nl.Item(0); //Hard coded count to zero
This time it worked. However I have a strong feeling I have just forced the
code to make it work (rather than using the methods "naturally" ) and
therefore this cannot be considered "production " strength.
Can anybody give me any pointers to what I am doing wrong please. Both with
the original "foreach" loop and the subsequent bodged "for" loop.
Thanks for any help.
Paul