将xml元素的内容读取为double

时间:2016-06-01 16:30:22

标签: c# xml

我想从XML文件中的数据创建对象列表。

public class Section //class description
{
   public string designation {get;set;}
   public double length {get;set;}
   public double crossSectionArea {get; set;}

   public Section CreateSection(string d,double l, double A)
   {
      return new Section
      {
         designation = d,
         length = l,
         crossSectionArea = A,
      };
    }

    Section(){}


}

XML文件看起来像这样

<Sections>
 <Section>
  <designation> Atx5E </designation>
  <length> 5.0 </length>
  <crossArea> 0.25 </crossArea>
 </Section>
 <!--- a lot of other Section elements with similar information!--->
</Sections>

我想使用XML文件中的数据创建List<Section>我正在使用XMLReader从文件中获取值。

static List<Section> LoadSections(string DataFile)//DataFile is string location of xml file
    {
        using (Stream stream = GetResourcesStream(DataFile))//returns a stream
        using (XmlReader xmlRdr = new XmlTextReader(stream))
            return
                (from SectionElem in XDocument.Load(xmlRdr).Element("Sections").Elements("Section")
                 select Section.CreateSection(
                    (string)SectionElem.Element("designation").Value,
                    (double)SectionElem.Element("length").Value,
                    (double)SectionElem.Element("crossArea").Value,
                 )).ToList();
    }

该方法不起作用,并且FormatExeption未处理错误。有没有办法将元素的内容检索为double? 。当我尝试将元素内容读为双精度时,我认为异常正在被提出。

1 个答案:

答案 0 :(得分:2)

不要使用Value属性,只需直接转换元素。

static List<Section> LoadSections(string dataFile)
{
    using (var stream = GetResourcesStream(dataFile))
    using (var reader = XmlReader.Create(stream))
        return
            (from e in XDocument.Load(reader).Elements("Sections").Elements("Section")
             select Section.CreateSection(
                (string)e.Element("designation"),
                (double)e.Element("length"),
                (double)e.Element("crossArea")
             )).ToList();
}