2016-06-01 9 views
2

XMLファイル内のデータからオブジェクトのリストを作成したいとします。xml要素の内容をdoubleとして読み取る

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ファイルには、私は、ファイルから値を取得するためのXMLReaderを使用しているXMLファイル内のデータを使用してList<Section>を作成したいこの

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

のように見えます。

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として取り出す方法はありますか? .Thats私は例外が発生していると思うとき、私はダブルとして要素の内容を読み込もうとします。

答えて

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(); 
} 
関連する問題