Search code examples
c#xmlxelement

Get the data of xelement in c#


I have this xml as you can see :

<ResultTest>
  <BackLeftShockAbsorber>0</BackLeftShockAbsorber>
  <BackRightBrak>0</BackRightBrak>
  <BackRightShockAbsorber>0</BackRightShockAbsorber>
  <BackShockAbsorber>0</BackShockAbsorber>
  <BackSideSlip>0</BackSideSlip>
  <BackWeight>0</BackWeight>
  <BrakeAcceleration>0</BrakeAcceleration>
  <CarReceiptionId>7</CarReceiptionId>
  <CO>0</CO>
  <CO2>0</CO2>
  <FrontBrake>0</FrontBrake>
  <FrontLeftBrake>0</FrontLeftBrake>
  <FrontLeftShockAbsorber>0</FrontLeftShockAbsorber>
  <FrontRightShockAbsorber>0</FrontRightShockAbsorber>
  <FrontShockAbsorber>0</FrontShockAbsorber>
  <FrontSideSlip>0</FrontSideSlip>
  <FrontWeight>0</FrontWeight>
  <FuelSystem>0</FuelSystem>
  <HandBrake>0</HandBrake>
  <HandBrake>0</HandBrake>
  <HandBrakeAcceleration>0</HandBrakeAcceleration>
  <HandBrakeLeft>0</HandBrakeLeft>
  <HandBrakeRight>0</HandBrakeRight>
  <LabelApplication>0</LabelApplication>
  <Lambda>0</Lambda>
  <NOX>0</NOX>
  <O2>0</O2>
  <Opacity>0</Opacity>
  <OutsideState>0</OutsideState>
  <PlayDetectorState>0</PlayDetectorState>
  <TechnicalReviewCenterLineId>0</TechnicalReviewCenterLineId>
  <TotalWeight>0</TotalWeight>
</ResultTest>

I want to get the data in each element as you can see here :

        float CurrentData = float.Parse(xd.Root.Elements("CO").ToString());

But i get this error :

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: Input string was not in a correct format.

Solution

  • Real simple to take this xml and put into a dictionary

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
    
                Dictionary<string, int> dict = doc.Descendants("ResultTest").Elements()
                    .GroupBy(x => x.Name.LocalName, y => (int)y)
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            }
        }
    }