0

I'm new in C# and want to sort an XML in memory by START Attribute but I need to take into account that when START_PLUSDAY Attribute exists.

Here is my XML:

<SCHEDULE>
   <PROGS>
      <PROG START="07:00:00" END="08:00:00">
          <ID></ID>
          <DATA>...</DATA>
             <STUFF>...</STUFF>
      </PROG>
      <PROG START="01:00:00" START_PLUSDAY="1" END="02:00:00" END_PLUSDAY="1">
          <ID></ID>
          <DATA>...</DATA>
             <STUFF>...</STUFF>
      </PROG>
   </PROGS>
</SCHEDULE>

The result I want should look like this:

<SCHEDULE>
   <PROGS>
      <PROG START="07:00:00" END="08:00:00">
          <ID></ID>
          <DATA>...</DATA>
             <STUFF>...</STUFF>
      </PROG>
      <PROG START="01:00:00" START_PLUSDAY="1" END="02:00:00" END_PLUSDAY="1">
          <ID></ID>
          <DATA>...</DATA>
             <STUFF>...</STUFF>
      </PROG>
   </PROGS>
</SCHEDULE>

1 Answer 1

1

Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
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);

            XElement progs = doc.Descendants("PROGS").FirstOrDefault();

            List<XElement> sortedProg = progs.Elements("PROG")
                .OrderBy(x => (int?)x.Attribute("START_PLUSDAY"))
                .ThenBy(x => (DateTime)x.Attribute("START")).ToList();
            XElement newProgs = new XElement("PROGS", sortedProg);

            progs.ReplaceWith(newProgs);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant. Thank you very much. For my use i can skip progs.ReplaceWith(newProgs); and just parse foreach (XElement xe in newProgs.Descendants("PROGRAMME")). Thanks again!!!

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.