未找到或创建XML

时间:2016-05-05 10:54:03

标签: 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;
using System.IO;
using System.Reflection;
using System.Xml;

namespace Students
{
    public partial class StudentDetails : Form
    {
        public StudentDetails()
        {
            InitializeComponent();
        }

        private void btnAddStudent_Click(object sender, EventArgs e)
        {
            XDocument studentXML = new XDocument("students")

            if (File.Exists("\\SR\\SR\\Student Records\\students.xml"))
            {
                 studentXML = XDocument.Load("\\SR\\SR\\Student Records\\students.xml");

            }
            else
            {
                studentXML = new XDocument(new XElement("students"));

            }

            ParameterPassing.studentNo = Microsoft.VisualBasic.Interaction.InputBox("Please enter Student Number", "Student Number");

            XElement xml = new XElement("student");
            xml.Add(new XElement("StudentNo", ParameterPassing.studentNo));

           if (studentXML.Descendants().Count() > 0)
            {
                studentXML.Descendants("students").First().Add(xml);
            }
            else
            {
                studentXML.Add(xml);
            }
            studentXML.Save("\\SR\\SR\\Student Records\\students.xml");
        }

        public void CreateDatabase()
        {
            DataSet ds = new DataSet();
            ds.ReadXml("\\SR\\SR\\Student Records\\students.xml");

            dgvMembers.DataSource = ds.Tables[0];
        }
    }
}

我的代码没有错误,它只是不打开创建或打开XML文档。

我手工制作了一个,看看是否有效,但也没有效果。

有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情......

        XDocument studentXML = new XDocument("students");

        foreach (DriveInfo drive in DriveInfo.GetDrives())
        {
            if (drive.DriveType == DriveType.Removable)
            {
                string XMLFilePath = String.Format("{0}{1}", drive.RootDirectory, "SR\\SR\\Student Records\\students.xml");
                if (File.Exists(XMLFilePath))
                {
                    studentXML = XDocument.Load(XMLFilePath);
                }
            }
        }