0

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>
3
  • Would this be of any use? stackoverflow.com/questions/1987470/… Commented Sep 13, 2016 at 15:58
  • Is the first firstname tag always the one you want? Commented Sep 13, 2016 at 16:02
  • Yes, the firstname tag is always the one I want. Commented Sep 13, 2016 at 17:08

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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);
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.