skip to Main Content

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


  1. 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>");
    
        var CritGroup = xdoc.Descendants("CritGroup")
            .Where(x => x.Attribute("CritGroupID").Value == "1").FirstOrDefault();
        
        CritGroup.Add(new XElement("Crit",
            new XAttribute("CritID","206")));
        
        Console.WriteLine(xdoc);
    }
    

    Output

    <Search Name="Test2" ProjTypeID="107">
      <CritGroup CritGroupID="1">
        <Crit CritID="205" />
        <Crit CritID="208" />
        <Crit CritID="206" />
      </CritGroup>
    </Search>
    
    Login or Signup to reply.
  2. you can try this code

        XmlElement newElement = xmlDoc.CreateElement("Crit");
        newElement.SetAttribute("CritId", "204");
    
        XmlNode CritGroupNode = xmlDoc["Search"]["CritGroup"];
        XmlElement groups = CritGroupNode["CritGroup"];
        CritGroupNode.InsertAfter(newElement, groups);
    
    Login or Signup to reply.
  3. I would use the XDocument solution in the other answer, but if that is not an option, this will insert a new Crit element last.

    XmlElement newNode = xmlDoc.CreateElement("Crit");
    newNode.SetAttribute("CritID", "206");
    
    XmlNode CritGroupNode = xmlDoc["Search"]["CritGroup"];
    CritGroupNode.InsertAfter(newNode, CritGroupNode.LastChild);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search