I want to add an XML fragment to the last element in an XML document, and I'm having problems, that is, the error I get:
"The node link is not a child of this node."
So my existing XML document is as follows:
<MAP> <LAYER name ="My first Layer"> <DATASET name="foo dataset" /> <SYMBOLOGY> <SYMBOL colour="red" /> </SYMBOLOGY> </LAYER> <LAYER name="My second Layer"> <DATASET name="bar dataset" /> <SYMBOLOGY> <SYMBOL colour="blue" /> </SYMBOLOGY> </LAYER> </MAP>
The XML fragment that I want to insert after the last LAYER element:
<LAYER name="My third Layer"> <DATASET name="whatever dataset" /> <SYMBOLOGY> <SYMBOL colour="yellow" /> </SYMBOLOGY> </LAYER>
The code I use is:
XmlDocumentFragment xmlDocFrag = xmlDocument.CreateDocumentFragment(); xmlDocFrag.InnerXml = inputXML; //which is basically the third layer example - see above. XmlElement rootElement = xmlDocument.DocumentElement; XmlNode lastLayerNode = rootElement.SelectSingleNode(@"//LAYER[last()]"); rootElement.InsertAfter(xmlDocFrag, lastLayerNode); //error raised here.
Any ideas on what I am doing wrong would be greatly appreciated. My XPath query seems to find, and it seems that it is choosing the right last layer, which it simply won't paste after it for some bizarre reason.
UPDATE / SOLUTION - How to do it with XPATH
Finally, it turned out that in XPath - see the code below, I think that basically there was no choice of the correct parent node in the first place, it is wrong to select the last LAYER, and then try InsertAfter () on this node. It is better to choose a level higher, i.e. MAP, then AppendChild (). See below:
XmlDocumentFragment xmlDocFrag = xmlDocument.CreateDocumentFragment(); xmlDocFrag.InnerXml = inputXML; XmlElement mapElement = (XmlElement)xmlDocument.SelectSingleNode(@"//MAP[last()]"); mapElement.AppendChild(xmlDocFrag);
Thanks to all the answers and help :)