Search code examples
c#asp.netxmllinq-to-xml

Add extra node in xml


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 !


Solution

  • It is very easy via LINQ to XML.

    c#

    void Main()
    {
        XDocument xdoc = XDocument.Parse(@"<Search Name='Test2' ProjTypeID='107'>
                <CritGroup CritGroupID='1'>
                    <Crit CritID='205'/>
                    <Crit CritID='208'/>
                </CritGroup>
            </Search>");
        xdoc.Dump("Before");
    
        XElement CritGroup = xdoc.Descendants("CritGroup")
            .Where(x => x.Attribute("CritGroupID").Value == "1").FirstOrDefault();
        
        CritGroup.Add(new XElement("Crit",
            new XAttribute("CritID","206"),
            new XAttribute("RelID","280"),
            new XAttribute("CompValue","11")));
        
        Console.WriteLine(xdoc);
    }
    

    Output

    <Search Name="Test2" ProjTypeID="107">
      <CritGroup CritGroupID="1">
        <Crit CritID="205" />
        <Crit CritID="208" />
        <Crit CritID="206" RelID="280" CompValue="11" />
      </CritGroup>
    </Search>