Raj
Raj

Reputation: 43

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# ?

Upvotes: 2

Views: 11477

Answers (1)

har07
har07

Reputation: 89325

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.

Upvotes: 9

Related Questions