-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
  • 51,408
  • 11
  • 123
  • 146
Dhara
  • 1,876
  • 2
  • 16
  • 35

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,158
  • 3
  • 30
  • 42
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,577
  • 6
  • 58
  • 90
Learner
  • 71
  • 12