c# - 将 xml 元素的内容读取为 double

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

我想创建一个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/

相关文章:

android - 更新的 SDK 管理器导致大量错误

c# - 如何自动更改文本框的语言

c# - 使用 C# 在 WinRT 应用程序中获取当前时间格式。

java - 如何使用 SAX XML Schema Validator 的验证消息进行内部化?

python - 合并 XML 文件并删除重复行

xml - 动态创建xml节点

java - 如何从 WSO2 ESB 应用程序生成的标记中删除 XML 属性?

c# - 从 FullyName 字符串到 Type 对象

c# - C#获取postgres表数据(CSV格式)

C#:函数中的函数可能吗?