I am trying to modify an xml and to add an extra node in it . So far I am able to add this node but I need a little tweak.
My sample XML
<Search Name="Test2" ProjTypeID="107">
<CritGroup CritGroupID="1" >
<Crit CritID="205"/>
<Crit CritID="208"/>
</CritGroup></Search>
I am able to add the extra node but I need to add it as the existing "Crit" Node format(Where there is no closing "Crit" instead /> is used). But I ended up with below output.
<Search Name="Test2" ProjTypeID="107">
<CritGroup CritGroupID="1" >
<Crit>CritID="206"</Crit>
<Crit CritID="205"/>
<Crit CritID="208"/>
</CritGroup> </Search>
I have used below code
XmlNode newNode = xmlDoc.CreateNode(XmlNodeType.Element, "Crit", "");
newNode.InnerText = "CritID="206" ";
XmlNode CritGroupNode = xmlDoc["Search"]["CritGroup"];
XmlElement groups = CritGroupNode["CritGroup"];
CritGroupNode.InsertAfter(newNode, groups);
Also is there any way to put the new node at the last ! For now its getting added as first? Thanks for reading and your help !
3
Answers
It is very easy via LINQ to XML.
c#
Output
you can try this code
I would use the
XDocument
solution in the other answer, but if that is not an option, this will insert a newCrit
element last.