I'm trying to sort the date-tags in my XML by value:
var noteElements = xDoc.Root.Descendants("Note").OrderBy(o => (DateTime)o.Element("date")).ToList();
foreach (XElement noteEl in noteElements)
{
string noteDateValue = noteEl.Element("date").Value;
noteEl.ReplaceWith(new XElement("notedate", noteEl, new XAttribute("date", noteDateValue)));
}
That doesn't work. The dates are not sorted as expected.
XML:
<Root>
<Notes>
<notedate date="date here"><Note>
<date>1997-07-04T00:00:00</date>
</Note></notedate>
<notedate date="date here"><Note>
<date>1997-06-04T00:00:00</date>
</Note></notedate>
</Notes>
</Root>
Anyone who can explain what I'm doing wrong?
You're replacing each Note
element with a notedate
element. The order in which you perform that replacement is irrelevant.
It sounds like you actually want something like:
var notes = doc.Root.Element("Notes");
notes.ReplaceNodes(notes.Elements()
.OrderBy(x => (DateTime) x.Element("date"))
.Select(x => new XElement("notedate",
new XAttribute("date", "date here"),
x));
See more on this question at Stackoverflow