用于更新/编辑XML数据的C#文本框

时间:2014-04-29 02:58:26

标签: c# xml textbox edit

    public void EditStudentRecord(string OldStudent, string NewStudent)
    {
        string strFilename = "Student_" + Tools.IDStudent + ".xml";
        if (File.Exists(strFilename))
        {
            XDocument xml = XDocument.Load(@"Student_" + Tools.IDStudent + ".xml");
            var query = from p in xml.Elements(strFilename).Elements("Student Name")

                        where (string)p.Element("Name") == OldStudent
                        select p;

            foreach (var record in query)

            {
                record.Element("Name").Value = NewStudent;
            }

            xml.Save(strFilename);
        }
    }

上面的代码将通过带有< Name >的ComboBox选项更新/编辑我的XML文件txtName.Text上的数据以更新新名称

当我把阿布汗改名为汗汉时

这是xml数据

<?xml version="1.0" encoding="UTF-8"?>
<Student_1.xml>
   <Student Name>
         <Name>Abu Khan</Name>         
         <Address>India</Address>
         <Grade>87</Grade>
   </Student Name>
</Student_1.xml>

和输出xml文件一旦编辑

<?xml version="1.0" encoding="UTF-8"?>
<Student_1.xml>
   <Student Name>
         <Name>Khan Han</Name>         
         <Address>India</Address>
         <Grade>87</Grade>
   </Student Name>
</Student_1.xml>

现在我的问题是如何使用更新XML上的< Address >< Grade >数据 2个文本框,txtAddress.Text表示地址,txtGrade.Text表示成绩

有人可以帮我修改上面的代码,以便我也可以编辑/更新< address >< grade >

1 个答案:

答案 0 :(得分:1)

这是一种更简单的方法:

将XML数据表示为对象

public class Student
{
  public  string Name;
  public  string Address;
  public  string Grade;
}

反序列化对象

Student student; 
 using (TextReader textReader = new StreamReader("pathToXMLFile"))
{
    XmlSerializer deserializer = new XmlSerializer(typeof(Student));
    student = (Student)deserializer.Deserialize(textReader);
}

将对象绑定到WinForm上的控件

textBox.DataBindings.Add("Text", student, "Name");

序列化对象以保存更改

using (TextWriter textWriter = new StreamWriter("yourFilePath"))
{
    XmlSerializer serializer = new XmlSerializer(typeof(Student));
    serializer.Serialize(textWriter, obj);
}