Bill
Bill

Reputation: 3509

Modify Xml using XDocument/XPath C#

I am wondering about XDocument possibilities in relation to xml and how it can modify xml. Let's assume I have next xml:

    <client>
        <firstName>Ian</firstName>
        <firstName>Charles</firstName>
        <city>LosAngeles</city>
        <state>California</state>
    </client>

Can I leave there only one "firstname" node (which is at the very top) by using XDocument or XPath operations? I want to do something like .Distinct() operation does in LINQ. I want to make my resulting xml look like this:

   <client>
       <firstName>Ian</firstName>
       <city>LosAngeles</city>
       <state>California</state>
   </client>

Upvotes: 0

Views: 324

Answers (2)

jdweng
jdweng

Reputation: 34421

Using xml linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            foreach(XElement client in doc.Descendants("client"))
            {
                List<XElement> firstNames = client.Elements("firstName").ToList();
                XElement newFirstName = new XElement(firstNames.FirstOrDefault());
                firstNames.Remove();
                client.AddFirst(newFirstName);
            }
        }
    }
}

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134801

Just search for all firstName elements within a client and remove all but the first. You can find all of the firstName elements to remove using this xpath query:

//client/firstName[position() > 1]

So just remove them.

doc.XPathSelectElements("//client/firstName[position() > 1]").Remove();

Upvotes: 2

Related Questions