Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 506
Happy Avatar asked Jun 01 '12 04:06

Happy


People also ask

Does LINQ work with XML?

The most important advantage of LINQ to XML is its integration with Language-Integrated Query (LINQ). This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes.

What is XElement C#?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


2 Answers

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.

like image 67
Pablo Romeo Avatar answered Oct 17 '22 14:10

Pablo Romeo


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");
like image 26
Martin Honnen Avatar answered Oct 17 '22 14:10

Martin Honnen