Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Element Node Value of XML using XElement in C#

Tags:

c#

xml

xelement

I have the following XML file saved:

<E:Events xmlns:E="Event-Details">
   <Date>12/27/2012</Date>
   <Time>‎11:12 PM</Time>
   <Message>Happy Birthday</Message>
</E:Events>

I am using XElement to load the above XML file. I want to get the Element Value of Date, Time and Message i.e. 12/27/2012, ‎11:12 PM and Happy Birthday. How can I retrieve these values. I have searched a lot on this but could not find anything.

Any help appreciated...

like image 452
Siddharth Avatar asked Dec 27 '12 06:12

Siddharth


People also ask

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.


1 Answers

Have you just tried getting the element from your XElement node?

XElement.Element(" < element name >");

will return the nodes you need.

Try the code below:

string text = "<E:Events xmlns:E=\"Event-Details\"><Date>12/27/2012</Date><Time>‎11:12 PM</Time><Message>Happy Birthday</Message></E:Events>";
XElement myEle = XElement.Parse(text);
Console.WriteLine(myEle.Element("Date").Value);
Console.WriteLine(myEle.Element("Time").Value);
Console.WriteLine(myEle.Element("Message").Value);
like image 72
Ravi Y Avatar answered Oct 05 '22 23:10

Ravi Y