Search code examples
c#xmlxml-parsinglinq-to-entitiesxmldocument

Replacing an xml element value in c#


Here is my xml file data

<Persons>
    <Person>
        <Name>john</Name>
    </Person>
    <Employee>
        <Detail>
            <Firstname>john</FirstName>
        </Detail>
    </Employee>
    <Student>
        <FullName>john</FullName>
    </Student>
</Persons>

I want to replace "john" to "danny" in all places.

How can I do this in c# ?


Solution

  • One possible way using XDocument :

    var doc = XDocument.Load("path_to_xml_file.xml");
    
    //select all leaf elements having value equals "john"
    var elementsToUpdate = doc.Descendants()
                              .Where(o => o.Value == "john" && !o.HasElements);
    
    //update elements value
    foreach(XElement element in elementsToUpdate)
    {
        element.Value = "danny";
    }
    
    //save the XML back as file
    doc.Save("path_to_xml_file.xml");
    

    Notice that XElement.Value contains all text nodes within the element, concatenated.

    The significance of this is, for example, considering your XML as input, not only <Name> has value of "john" but also <Person>. But we only want to update the leaf elements not the ancestors.

    *) I assumed you didn't really meant to tag the question by so this answer using the newer XML API XDocument, though using XmlDocument is also possible.