我想根据 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>
我想创建一个List<Section>
使用 XML 文件中的数据我使用 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 形式检索元素的内容?当我尝试将元素内容读取为 double 时,我认为这是引发异常的地方。
最佳答案
不要使用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();
}
关于c# - 将 xml 元素的内容读取为 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37574175/