【问题标题】:c# Linq and Xml Reading时间:2019-01-01 标签:c#linq and xmlreading
【发布时间】:2016-04-07 20:08:12
【问题描述】:
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 文件并将其发布到一个有五列的列表视图中。我有这个错误要修复并尝试只导入文件。

【问题讨论】:

  • 你能包围在 try catch 中并发布堆栈跟踪吗?
  • XML 文件是什么样的?
  • 确保您没有房地产中常见的 1/2 浴室或卧室。
  • @Craig 调试你的代码,看看错误发生时House.Element("Bedrooms").Value 的值是多少

标签: c# xml linq


【解决方案1】:

您可能需要考虑使用 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() 来避免任何编译器问题。

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多