简体   繁体   English

在使用LINQ:XML创建类的实例方面需要帮助

[英]need help using LINQ:XML to create an instance of a class

I have a class which defines meteorological measurements with an API. 我有一个用API定义气象测量的类。 I have created classes to store these measurements within an XML file. 我创建了将这些度量存储在XML文件中的类。 I have been able to write to the XML file, but am unable to read from it. 我已经能够写入XML文件,但是无法读取它。 I need to be able to read the data, then instantiate the Measurement Class via the constructor, and then add these instances to a List Here is the code for the Measurement constructor 我需要能够读取数据,然后通过构造函数实例化Measurement Class,然后将这些实例添加到列表中这是Measurement构造函数的代码

  public Measurement(string longit, string latitud, string cty, string pcode, DateTime dte, decimal huy, decimal pre, string windDir, int windSp) : base(longit, latitud, cty,pcode)
    {

        dte = date;
        huy = humidity;
        pre = precipitation;           
        windDir = windDirection;
        windSp = windSpeed;
    }

and here is a sample of the XML file 这是XML文件的示例

<Measurement>
<longitude>-76.2858726</longitude>
<latitude>36.8507689</latitude>
<city>Thetford</city>
<postcode>IP24 1ED</postcode>
<date>01/04/2011</date>
<windDirection>SE</windDirection>
<windSpeed>8</windSpeed>
<humidity>2.6</humidity>
<precipitation>0.0</precipitation>
</Measurement>

And here is the method I have written to read the file, and make an instance of the class Measurement. 这是我编写的读取文件并制作Measurement类的实例的方法。 I receive no errors, however have not managed to create the List<> 我没有收到任何错误,但是没有成功创建List <>

public List<Measurement> GetList()
    {
        List<Measurement> measurements = new List<Measurement>();
        XDocument doc = XDocument.Load(@"C:\Users\Sonya\Documents\Visual Studio 2010\Projects\WeatherAPI\WeatherAPI\measurement_store.xml");
        XElement root = doc.Root;

     var d = (from s in root.Descendants("Measurement")
                 select new Measurement
                 {
                     Longitude = s.Element("longitude").Value,
                     Latitude = s.Element("latitude").Value,
                     City = s.Element("city").Value,
                     Postcode = s.Element("postcode").Value,
                     Date = DateTime.Parse(s.Element("date").Value),
                     Humidity = decimal.Parse(s.Element("humidity").Value),
                     Precipitation = decimal.Parse(s.Element("precipitation").Value),
                     WindSpeed = Convert.ToInt32(s.Element("windSpeed").Value),
                     WindDirection = s.Element("windDirection").Value,

                 }).ToList();


     d.ForEach(measurements.Add);

        return measurements;
    }//end GetList()

I've also written another method, of a slightly different format.. 我还写了另一种格式稍有不同的方法。

public List<Measurement> createXMLListMeasurements()
    {
        //load the xml document
        XDocument doc = XDocument.Load(@"C:\Users\Sonya\Documents\Visual Studio 2010\Projects\WeatherAPI\WeatherAPI\measurement_store.xml");
        //XElement root = doc.Root;

        //instantiate a new list of measurements
        List<Measurement> measurements = new List<Measurement>();

            //get a list of measurement elements
           var d = from s in doc.Descendants("Measurement")
                    //where
                    select new 
                    { //assign Measurement variables to data from xml doc
                        Longitude = (string)s.Element("longitude").Value,
                        Latitude = (string)s.Element("latitude").Value,
                        City = (string)s.Element("city").Value,
                        Postcode = (string)s.Element("postcode").Value,
                        Date = DateTime.Parse(s.Element("date").Value),
                        Humidity = decimal.Parse(s.Element("humidity").Value),
                        Precipitation = decimal.Parse(s.Element("precipitation").Value),
                        WindSpeed = Convert.ToInt32(s.Element("windSpeed").Value),
                        WindDirection = (string)s.Element("windDirection").Value,
                    };

           foreach (var s in d)
           {   //for each element found, instantiate Measurements class, and add to the measurements list.
               Measurement m = new Measurement(s.Longitude, s.Latitude, s.City, s.Postcode, s.Date, s.Humidity, s.Precipitation, s.WindDirection, s.WindSpeed);
               measurements.Add(m);

           }


        return measurements;
    }

Apologies if these questions seem silly, am VERY new to LINQ and XML, so finding my way very slowly..any help much appreciated! 抱歉,如果这些问题看起来很愚蠢,对LINQ和XML还是很陌生的,所以慢慢找到我的方式。 A console application calls this method for testing and produces nothing but WeatherAPI.Measurement WeatherAPI.Measurement 控制台应用程序调用此方法进行测试,只产生WeatherAPI.Measurement WeatherAPI.Measurement

Help? 救命? thanks! 谢谢!

Overall, your code looks fine. 总体而言,您的代码看起来不错。 As Jon Skeet pointed out in his comment, you don't need to bother adding each element to a list -- you can simply return the result of the query after calling .ToList() . 正如Jon Skeet在其评论中指出的那样,您无需费心将每个元素添加到列表中-您可以在调用.ToList()之后简单地返回查询结果。

Most likely, there's either something wrong with your xml file, or you're reading it incorrectly. 很有可能是您的xml文件有问题,或者您读取的是错误的。

If your xml file is truly just: 如果您的xml文件确实是:

<Measurement>
    <longitude>-76.2858726</longitude>
    <latitude>36.8507689</latitude>
    <city>Thetford</city>
</Measurement>

Then your code won't work, because the root of the xml file is Measurement . 然后您的代码将无法工作,因为xml文件的目录为Measurement Therefore, calling doc.Root.Descendants("Measurement") will give you 0 results. 因此,调用doc.Root.Descendants("Measurement")将得到0个结果。 Instead, your xml file should have a unique root element, for example: 相反,您的xml文件应具有唯一的根元素,例如:

<root>
    <Measurement>
        <longitude>-76.2858726</longitude>
        <latitude>36.8507689</latitude>
        <city>Thetford</city>
    </Measurement>
    <Measurement>
        <longitude>-71.2858726</longitude>
        <latitude>32.1507689</latitude>
        <city>Other City</city>
    </Measurement>
</root>

Furthermore, you don't need to bother obtaining the Root of the xml document. 此外,您无需费心获取xml文档的Root If all you want to do is find elements named Measurement , just say doc.Descendants("Measurement") . 如果您只想查找名为Measurement元素,只需说doc.Descendants("Measurement")

Try this code with the above xml file: 使用上面的xml文件尝试以下代码:

void Main()
{
    var measurements = GetMeasurements(@"C:\path\to\file\measurements.xml");
}

public List<Measurement> GetMeasurements(string path)
{
    XDocument doc = XDocument.Load(path);

    return (from s in doc.Descendants("Measurement")
            select new Measurement
            {
                 Longitude = Convert.ToDecimal(s.Element("longitude").Value),
                 Latitude = Convert.ToDecimal(s.Element("latitude").Value),
                 City = s.Element("city").Value,
            }).ToList();
}

public class Measurement
{
    public decimal Longitude { get; set; }
    public decimal Latitude { get; set; }
    public string City { get; set; }
}

When I run it in LINQPad, I get the following result: 在LINQPad中运行它时,得到以下结果:

样本结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM