读取XML文件以基于索引进行列表

问题描述 投票:-1回答:1

我正在尝试将XML文件读入类成员列表。这是我的代码

public void readXml()
{
      List<DewesoftDevices> dewesoftDevices = GetDeviceList();
}

private List<DewesoftDevices> GetDeviceList()
{
   var devices = from y in xdoc.Descendants("DewesoftSetup").Descendants("Slot")
                 select new DewesoftDevices
                 {
                    slotNum = y.Attribute("Index").Value,
                    measuredValue = y.Element("MeasuredValue").Value
                 };
   return devices.ToList();
}

这里是Dewesoft Device类

public class DewesoftDevices
{
   public string slotNum;
   public string measuredValue;
}

这里是xml的一部分

<DewesoftSetup>
            <Devices>
                <StartStoreTime>43861.6768385532</StartStoreTime>
                <SampleRate>100</SampleRate>
                <BlockSize>1000</BlockSize>
                <IBRate>10</IBRate>
                <MaxSampling>40000</MaxSampling>
                <StartZoomTime>-10</StartZoomTime>
                <EndZoomTime>-10</EndZoomTime>
                <Device Type="AI">
                    <Slot Index="0">
                        <MeasuredValue>TEMPERATURE</MeasuredValue>
                        <Range>K: -270..1372</Range>
                        <LPFilter_Hz>AUTOMATIC</LPFilter_Hz>
                        <CustomRange>10</CustomRange>
                        <OutputChannel>
                            <DisplayColor>#00FF00</DisplayColor>
                            <Name>TC-09-1K</Name>
                            <Description></Description>
                            <DefaultUnit>False</DefaultUnit>
                            <Unit>°F</Unit>
                            <UserScaleMin>0</UserScaleMin>
                            <UserScaleMax>2500</UserScaleMax>
                        </OutputChannel>  
                </Slot>
         </Device>
    </Devices>
</DewesoftSetup>

有很多(大约50个,但可以更改),我正在尝试以此为基础构建列表。

失败]

measuredValue = y.Element("MeasuredValue").Value
System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Xml.Linq.XContainer.Element(...) returned null.

我正在尝试将XML文件读入类成员列表。这是我的代码public void readXml(){List dewesoftDevices = GetDeviceList(); }私有列表<...>

c# linq-to-xml
1个回答
0
投票

尝试xdoc.Descendants("Slot")

© www.soinside.com 2019 - 2024. All rights reserved.