You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法解析XML并将航班数据导入DataGridView的技术求助

Fixing XML Parsing & DataGridView Binding Issue

Let's work through this step by step—your current code has a few clear issues causing the parsing error, plus you haven't accounted for mapping all the instructor/student data you need for your DataGridView columns. Here's how to fix it:

First, Why Your Current Code Fails

  • Wrong XML loading method: XmlDocument.LoadXml() expects an XML string, but you're passing a file path. You need XmlDocument.Load() instead.
  • Invalid LINQ syntax: Your Select call is malformed (you can't pass multiple attributes like that), and XmlDocument doesn't even have a Descendants() method—that's part of LINQ to XML's XDocument class.
  • Incomplete data extraction: You aren't pulling the instructor/student number and name details required for your target columns.

Working Solution Using LINQ to XML

This approach is cleaner for querying XML and maps all your required columns properly:

using System.Linq;
using System.Xml.Linq;
using System.Data;
using System.Windows.Forms;

// Inside your form method (e.g., a button click handler)
string inputPath = Application.StartupPath + "\\Data.xml";
try
{
    // Load XML file with XDocument (optimized for LINQ queries)
    XDocument doc = XDocument.Load(inputPath);

    // Query XML to extract all required flight data
    var flightData = from flight in doc.Descendants("Flight")
                     let instructor = flight.Element("Instructor")
                     let student = flight.Element("Student")
                     select new
                     {
                         FlightId = flight.Attribute("ID")?.Value,
                         FlightDescription = flight.Attribute("Description")?.Value,
                         FlightDate = flight.Attribute("Date")?.Value ?? "No date specified",
                         InstructorNum = instructor?.Attribute("Num")?.Value,
                         InstructorName = $"{instructor?.Element("Name")?.Value} {instructor?.Element("Surname")?.Value}".Trim(),
                         StudentNum = student?.Attribute("Num")?.Value,
                         StudentName = $"{student?.Element("Name")?.Value} {student?.Element("Surname")?.Value}".Trim()
                     };

    // Create DataTable matching your target columns
    DataTable flightTable = new DataTable();
    flightTable.Columns.Add("flight_id", typeof(string));
    flightTable.Columns.Add("flight_description", typeof(string));
    flightTable.Columns.Add("flight_date", typeof(string));
    flightTable.Columns.Add("instructor_num", typeof(string));
    flightTable.Columns.Add("instructor_name", typeof(string));
    flightTable.Columns.Add("student_num", typeof(string));
    flightTable.Columns.Add("student_name", typeof(string));

    // Populate the DataTable
    foreach (var flight in flightData)
    {
        flightTable.Rows.Add(
            flight.FlightId,
            flight.FlightDescription,
            flight.FlightDate,
            flight.InstructorNum,
            flight.InstructorName,
            flight.StudentNum,
            flight.StudentName
        );
    }

    // Bind to DataGridView
    dataGridView1.DataSource = flightTable;
}
catch (Exception ex)
{
    MessageBox.Show($"Error loading data: {ex.Message}");
}

Key Details & Fixes

  • Safe null handling: Uses ?. to avoid crashes if any element/attribute is missing (like the Date attribute in your second <Flight> entry).
  • Full data mapping: Combines Name and Surname for instructor/student names (adjust this if you only need one field) and extracts the Num attributes.
  • Proper XML loading: XDocument.Load() correctly reads the file instead of trying to parse a file path as XML text.

Alternative: Using XmlDocument (If You Prefer)

If you want to stick with XmlDocument instead of LINQ to XML, here's a working version:

using System.Xml;
using System.Data;
using System.Windows.Forms;

string inputPath = Application.StartupPath + "\\Data.xml";
try
{
    XmlDocument doc = new XmlDocument();
    doc.Load(inputPath);
    XmlNodeList flightNodes = doc.SelectNodes("//Flight");

    DataTable flightTable = new DataTable();
    // Add columns same as above...

    foreach (XmlNode flightNode in flightNodes)
    {
        string flightId = flightNode.Attributes["ID"]?.Value;
        string flightDesc = flightNode.Attributes["Description"]?.Value;
        string flightDate = flightNode.Attributes["Date"]?.Value ?? "No date specified";

        XmlNode instructorNode = flightNode.SelectSingleNode("Instructor");
        string instructorNum = instructorNode?.Attributes["Num"]?.Value;
        string instructorName = $"{instructorNode?.SelectSingleNode("Name")?.InnerText} {instructorNode?.SelectSingleNode("Surname")?.InnerText}".Trim();

        XmlNode studentNode = flightNode.SelectSingleNode("Student");
        string studentNum = studentNode?.Attributes["Num"]?.Value;
        string studentName = $"{studentNode?.SelectSingleNode("Name")?.InnerText} {studentNode?.SelectSingleNode("Surname")?.InnerText}".Trim();

        flightTable.Rows.Add(flightId, flightDesc, flightDate, instructorNum, instructorName, studentNum, studentName);
    }

    dataGridView1.DataSource = flightTable;
}
catch (Exception ex)
{
    MessageBox.Show($"Error loading data: {ex.Message}");
}

Either approach will resolve your parsing error and populate the DataGridView with all the flight information you need.

内容的提问来源于stack exchange,提问作者mert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 14:32:44