My LINQ to XML Experience : Node Value Extractions

For those who had been accustomed to the use of XML DOM perhaps you may have experienced the tedious job of extracting to converting node values . This sample will simply show us how extracting is easily done on LINQ .

Example 1 : Extracting string values.
XElement stringElement=
   new XElement("Name","Marvin");          
Console.WriteLine(stringElement);
Console.WriteLine((string)stringElement);

Result 1:
<Name>Marvin</Name>
Marvin

Example 2 : Working with double values
XElement doubleElement=
   new XElement("Value",1.2345678);
Console.WriteLine(doubleElement);
Console.WriteLine((double)doubleElement);

Result 2:
<Value>1.2345678</Value>
1.2345678

Example 3: Converting from one type to another
XElement castElement=
   new XElement("Condition","TRUE");
Console.WriteLine(castElement);
Console.WriteLine((bool)castElement);

Result :
<Condition>true</Condition>
True


But this statement will produce an exception because the string TUE is not a valid boolean value .
XElement castElement=
   new XElement("Condition","TUE");
Console.WriteLine(castElement);
Console.WriteLine((bool)castElement);

An easier life with XML I supposed . While the example are pretty simple , the idea that it wants to convey is already there .

Happy coding ....

Comments