How to Read a specific element value from XElement in LINQ to XML

Happy picture Happy · Jun 1, 2012 · Viewed 17.8k times · Source

I have an XElement which has content like this.

<Response xmlns="someurl" xmlnsLi="thew3url">
   <ErrorCode></ErrorCode>
   <Status>Success</Status>
   <Result>
       <Manufacturer>
            <ManufacturerID>46</ManufacturerID>
            <ManufacturerName>APPLE</ManufacturerName>
       </Manufacturer>
      //More Manufacturer Elements like above here
   </Result>
</Response>

How will i read the Value inside Status element ?

I tried XElement stats = myXel.Descendants("Status").SingleOrDefault(); But that is returning null.

Answer

Pablo Romeo picture Pablo Romeo · Jun 1, 2012

If myXel already is the Response XElement then it would be:

var status = myXel.Elements().Where(e => e.Name.LocalName == "Status").Single().Value;

You need to use the LocalName to ignore namespaces.