Search code examples
c#asp.netxml

how to modify contents in a nested xml


I need to modify the CompValue from "C02" to "C02,C03" . How to achieve this ?I have tried various ways to modify the XML content but so far could not find a solution.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("XML value");

XmlNode root = xmlDoc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::CompValue");
myNode.Value = "blabla";

Also

root.SelectSingleNode("//CritGroup/Crit").InnerText = "NewValue";

This is my sample xml

<Search Name="Test1" ProjTypeID="107">
    <SearchType SearchTypeID="20246" />
    <FiscalYear Year="2022" />
    <CorpEnt CEID="367" CEName="Sample" />
    <CritGroup CritGroupID="1" CritGroupAndOr="AND">
        <Crit CritID="205" RelID="275" CompValue="C02" CompValueHuman="C02" AndOr="AND" TextBoxName="tbProjNum" /> 
        <Crit CritID="208" RelID="280" CompValue="11" CompValueHuman="Yes" AndOr="AND" TextBoxName="" />
    </CritGroup>
    <PageSize Size="200" />
</Search>

Solution

  • You need to get the complete node and replace the attribute. Here is the example

        var xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml);
    
        var critNode = xmlDoc.SelectSingleNode("//Crit[@CompValue='C02']");
    
        if (critNode != null)
        {
            var compValueAttr = critNode.Attributes["CompValue"];
            if (compValueAttr != null)
            {
                compValueAttr.Value = "C02,C03";
            }
        }
    
        var modifiedXml = xmlDoc.OuterXml;
        Console.WriteLine(modifiedXml);