Tuesday, 3 February 2015

how do I link the class with main method in the same file



This is my first time using C# to create the program. How do I GetXMLData then add the record after that update the data in xml file? This program do not return me the error, but I could not see the data id "4" has been added into the record.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;


namespace LinQ
{
class Program
{

private string path = "TestData.xml";

private void GetXMLData()
{
// try
// {
XDocument testXML = XDocument.Load(path);
var students = from student in testXML.Descendants("Student")
select new
{
ID = Convert.ToInt32(student.Attribute("ID").Value),
Name = student.Element("Name").Value
};

foreach (var student in students)
{
// Do other operations with each student object

}
// }
//catch (Exception err)
//{
// MessageBox.Show(err.Message);
//}
}
private void InsertXMLData(string name)
{
//try
//{
XDocument testXML = XDocument.Load(path);

XElement newStudent = new XElement("Student",
new XElement("Name", name)
);
var lastStudent = testXML.Descendants("Student").Last();

int newID = Convert.ToInt32(lastStudent.Attribute("ID").Value);
newStudent.SetAttributeValue("ID", 4);
testXML.Element("Students").Add(newStudent);
testXML.Save(path);
//}
//catch (Exception err)
//{
// MessageBox.Show(err.Message);
//}
}

private void UpdateXMLData(string name, int id)
{
//try
//{
XDocument testXML = XDocument.Load(path);
XElement cStudent = testXML.Descendants("Student").Where(c => c.Attribute("ID").Value.Equals(id.ToString())).FirstOrDefault();

cStudent.Element("Name").Value = name;
testXML.Save(path);
//}
//catch (Exception err)
//{
// MessageBox.Show(err.Message);
//}
}

static void Main(string[] args)
{
//GetXMLData();
//InsertXMLData(string name);


}

}
}

No comments:

Post a Comment