Search code examples
c#-4.0linq-to-xmlxelement

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


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.


Solution

  • XElement response = XElement.Load("file.xml"); // XElement.Parse(stringWithXmlGoesHere)
    XNamespace df = response.Name.Namespace;
    XElement status = response.Element(df + "Status");
    

    should suffice to access the Status child element. If you want the value of that element as a string then do e.g.

    string status = (string)response.Element(df + "Status");