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>XX99 9XX</Postcode>
</Address>
</Premises>
</Property>
I am trying to add two new endorsements, as follows:
<Endorsement>
<ShortWording>sa</ShortWording>
<Wording>wa</Wording>
</Endorsement>
<Endorsement>
<ShortWording>sb</ShortWording>
<Wording>wb</Wording>
</Endorsement>
So initially I tried the following code:
XmlDocument doc = new XmlDocument();
doc.Load("in.xml"); //Contains the base XML shown above
string insertionPoint = "/*/Premises/Endorsement[1]";
XmlNode childNode = doc.SelectSingleNode(insertionPoint);
XmlElement endorsements = doc.CreateElement("e");
endorsements.InnerXml =
"<Endorsement><ShortWording>sa</ShortWording><Wording>wa</Wording></Endorsement><Endorsement><ShortWording>sb</ShortWording><Wording>wb</Wording></Endorsement>";
foreach(XmlNode insertNode in endorsements.ChildNodes)
{
doc.SelectSingleNode(insertionPoint).ParentNode.In sertAfter(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.ChildNodes;
for (int count = 0; count <= nl.Count; count++)
{
XmlNode insertNode = nl.Item(count);
doc.SelectSingleNode(insertionPoint).ParentNode.In sertAfter(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