Update Duplicate XML Node using C#.NET

The below code will help you update duplicate XML nodes.Suppose if you have an XML file like below

<?xml version=”1.0″ encoding=”utf-8″ ?>
<book>
<name>XML and related technologies</name>
<author> Atul Kahate</author>
<author>Achyut Godbole</author>
<pages>500</pages>
</book>

You can update the duplicate author node by using the below method

public static bool UpdateDuplicateXml(string xmlFilePath)
{
try
{
XDocument xml = XDocument.Load(xmlFilePath);
var dubs = xml.Descendants().Where(x => x.Name == "author");
var xElements = dubs as XElement[] ?? dubs.ToArray();
if (xElements.Count() > 1)
{
for (int index = 0; index < xElements.Length; index++)
{


if (index == 0)
{
XElement xElement = xElements[index];
xElement.Name = xElement.Name;
}
else
{
XElement xElement = xElements[index];
int newIndex = index + 1;
xElement.Name = xElement.Name + newIndex.ToString();
}


}
}
xml.Save(xmlFilePath);
return true;
}
catch(Exception exception)
{
return false;
}
}
Output

<?xml version=”1.0″ encoding=”utf-8″?>
<book>
<name>XML and related technologies</name>
<author> Atul Kahate</author>
<author2>Achyut Godbole</author1>
<pages>500</pages>
</book>

Enjoy coding…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s