Click here to Skip to main content
15,896,207 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I am trying to change the name of xml tag where two siblings are having same name.
Example:
consider following part of xml document

<book>
<name>XML and related technologies</name>
<author> Atul Kahate</author>
<author>Achyut Godbole</author>
<pages>500</pages>
</book>

Here there are 2 tags with name author which are siblings of each other so name of one tag should be changed to say author2.
I am using XElement class.
Please help me.

Thanks in advance.
Posted

1 solution

You can update Duplicate xml nodes by using the below method
C#
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;
            }
        }

Hope this helps
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900