Magesh K
Magesh K

Reputation: 37

C# Find and replace data inside XML tag

Xml File :

<?xml version="1.0" encoding="iso-8859-1"?>
<ResDoc>
<Summary>
My name is Magesh
</Summary>
</ResDoc>

How to find the data "Magesh" inside Summary tag and replace it as "GivenName".

A c# code to load XML file, find and replace.

I have tried to loading xml file using XMLDocument, find and replace. But it is not expected.

xdoc = new XmlDocument {PreserveWhitespace = true};
xdoc.LoadXml(taggedresume);
string Name1 = "Magesh";

foreach (XmlNode var in xdoc.SelectSingleNode("//ResDoc/summary"))
{
 var.InnerXml.Replace(Name1, "GivenName");                   
}

Upvotes: 0

Views: 3087

Answers (1)

mybirthname
mybirthname

Reputation: 18127

    static void Main(string[] args)
    {
        string xml = @"<?xml version=""1.0"" encoding=""iso-8859-1""?>
<ResDoc>
<Summary>
My name is Magesh
</Summary>
</ResDoc>";

        XDocument doc = XDocument.Parse(xml);

        var element = doc.Element("ResDoc").Element("Summary");

        element.Value = element.Value.Replace("Magesh", "YourName");

        Console.WriteLine(element.Value);
        Console.ReadKey();

    }

Here an example, next time try something by yourself first. You need to have reference to System.Xml.Linq;

Upvotes: 1

Related Questions