-1

give me please advice. I have this xml document:

 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
  <!--This is an XML Generated File-->
    <DataGrid279.RecordStore>
     <StoreS Month="březen">
       <Date>7.3.2014</Date>
       <Amount>56</Amount>
     </StoreS>
     <StoreS Month="březen">
       <Date>7.3.2014</Date>
       <Amount>56</Amount>
     </StoreS>
     <StoreS Month="březen">
       <Date>7.3.2014</Date>
       <Amount>67</Amount>
     </StoreS>
   </DataGrid279.RecordStore>

I just wanna to sort this xml document and sorted result write back to the document. The exception NullReferenceException is being called when I use in labeled(**) line property Value which is reffered to Null. When I remove property Value the code is executed. How can I set property Value to correctly code executing?

public void Sort(string PATH,string month)
{
  XDocument doc = XDocument.Load(PATH);            
  **doc.Element("DataGrid279.RecordStore").ReplaceNodes(doc.Element("DataGrid279.RecordStore").Elements("StoreS").OrderBy(StoreS => StoreS.Attribute(month)));
  doc.Save(PATH);
}

Thanks

2 Answers2

0

Though it's only an educated guess, the OrderBy is almost certainly the issue:

OrderBy(StoreS => StoreS.Attribute(month))

Here you are actually looking for an attribute with the name of whatever is passed in. I think the code you really want looks like this:

doc.Element("DataGrid279.RecordStore").ReplaceNodes(
    doc.Element("DataGrid279.RecordStore").Elements("StoreS")
        .OrderBy(StoreS => StoreS.Attribute("Month").Value));
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
0

You are trying to order by XAttribute (which is not comparable). You should order by its value (I recommend to use casting when you read node value to avoid NullReferenceException):

var doc = XDocument.Load(PATH);
doc.Root.ReplaceAll(doc.Root.Elements().OrderBy(s => (string)s.Attribute("Month")));
doc.Save(PATH);

Also all StoreS in your sample xml have same value of Month - not best sample data to check sorting.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459