无法解析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 needXmlDocument.Load()instead. - Invalid LINQ syntax: Your
Selectcall is malformed (you can't pass multiple attributes like that), andXmlDocumentdoesn't even have aDescendants()method—that's part of LINQ to XML'sXDocumentclass. - 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 theDateattribute in your second<Flight>entry). - Full data mapping: Combines
NameandSurnamefor instructor/student names (adjust this if you only need one field) and extracts theNumattributes. - 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
相关产品推荐
相关产品推荐

