c#Linq和Xml Reading

时间:2016-04-07 20:08:13

标签: c# xml linq

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AS3_S5_CraigFenton
{
    public partial class Form1 : Form
    {
        List<House> houseListings = new List<House>();

        public Form1()
        {
            InitializeComponent();
        }

        private void buttongetListings_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                XElement root = XElement.Load(openFileDialog1.FileName);

                foreach(var House in root.Elements("House"))
                {
                    House h = new House();

                    h.HouseCode = House.Element("HouseCode").Value;
                    h.HouseType = House.Element("HouseType").Value;
                    h.Neighborhood = House.Element("HouseNeighborhood").Value;
                    h.Price = decimal.Parse(House.Element("Price").Value);
                    h.Bedrooms = int.Parse(House.Element("Bedrooms").Value);

                    houseListings.Add(h);
                }

                listViewlistings.Items.Clear();

                var sortedHouse =
                    from House in houseListings
                    orderby House.HouseType, House.Price
                    select House;

                foreach (House h in sortedHouse)
                {
                    ListViewItem listingsItem = new ListViewItem();

                    listingsItem.Text = h.HouseCode;
                    listingsItem.SubItems.Add(h.HouseType);
                    listingsItem.SubItems.Add(h.Neighborhood);
                    listingsItem.SubItems.Add(h.Price.Tostring(0));
                    listingsItem.SubItems.Add(h.Bedrooms.Tostring());

                }


            }
        }
    }
}

我得到的错误是Int.parse无法转换为.tostring?我究竟做错了什么。我正在尝试读取xml文件并将其发布到具有五列的列表视图中。我有这个错误要修复并尝试导入文件。

1 个答案:

答案 0 :(得分:0)

您可能需要考虑使用Int32.TryParse()方法,该方法将评估并返回一个布尔值,以指示您的值是否可以正确解析:

int bedrooms;
if(Int32.TryParse(House.Element("Bedrooms").Value, out bedrooms))
{
     // Your parse was successful, so set it
     h.Bedrooms = bedrooms;
}
else
{
     // Otherwise it wasn't in the correct format (a breakpoint
     // here would be useful
}

然而,任何房间号码的使用可能都表示为双倍(例如2.5间卧室或3.5间浴室),因此您可能需要考虑如何处理这些,因为这些是常见情况。

此外,您需要对.Tostring()进行一些调用,您应确保使用正确的.ToString()来避免任何编译器问题。