c#获取xelement的数据

Get the data of xelement in c#

如您所见,我有这个 xml :

<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>

我想获取每个元素中的数据,如您所见:

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

但是我得到这个错误:

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.

拿这个 xml 并放入字典非常简单

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());
        }
    }
}