-1

I have a code like:

jobdetails.group = TM_item.Group_xml.ToString(); //XML
var xDoc = XDocument.Parse(jobdetails.group);
var data = xDoc.Root.Elements().OrderBy(x => (string)x.Attribute("name"));

XML:

<Groups>
      <Group name="Front0">
        <Room_type>Front</Room_type>
        <Dimension>Not available</Dimension>
        <Status>PENDING</Status>
        <Notes>None</Notes>
        <User>r2g</User>
        <Audio_length>00:00:00</Audio_length>
        <Image_count>1</Image_count>
        <Section_count>0</Section_count>
      </Group>
</Groups>

I want to put where condition in xDoc.Root.Elements(),

I tried xDoc.Root.Elements().OrderBy(x => (string)x.Attribute("name")).Where(x => (string)x.Attribute("User").Value == loggedin_user); but it doesnot give me output..I am getting Object reference not set to an instance of an object. any suggestion?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Dhara
  • 1,914
  • 2
  • 18
  • 37

2 Answers2

0

You are accessing Attribute("User") of Attribute("name"), then you are accessing user's property Value. One of these is null.

Try to construct a query which looks for elements with attribute name missing, or such that return an element with User attribute missing. I suppose you will find the guilty element.

Then reformat your query to protect, e.g. by adding Where(at => at != null) before accessing its properties.

Zoran Horvat
  • 10,924
  • 3
  • 31
  • 43
0

Use FirstOrDefault to get null when there is no result:

XElement value =  xdoc.Descendants()
    .Elements("Group")
    .Where(i => i.Attribute("name").Value == "Front0")
    .OrderBy(i => i.Attribute("name").Value)
    .FirstOrDefault();
thomasb
  • 5,816
  • 10
  • 57
  • 92
Learner
  • 71
  • 13