zdsnide
zdsnide

Reputation: 51

Appending Nodes to an XML file

I have an XML file that contains elements of a school.

 <Classrooms>
  <Classroom ID="Mrs.S">
   <Students>
    <Student>
     <Name> Billy Blue </Name>
     <Grade> 1 </Grade>
     <Sex> Male </Sex>
     <Age> 7 </Age>
     <Picture> c:/School/Students/BillyBlue </Picture>
   </Student>
  </Students>
 </Classroom>
</Classrooms>

I want to append different students as i go along with a windows form. Here is my code. They are currently being added after the Classroom tag and i want them within the Students node.

    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(ConfigurationManager.AppSettings.Get("studentFile"));
        XmlNode student = xmlDoc.CreateElement("Student");
        XmlNode name = xmlDoc.CreateElement("Name");
        name.InnerText = tBName.Text;
        student.AppendChild(name);
        XmlNode grade = xmlDoc.CreateElement("Grade");
        grade.InnerText = tBGrade.Text;
        student.AppendChild(grade);
        XmlNode sex = xmlDoc.CreateElement("Sex");
        sex.InnerText = tbSex.Text;
        student.AppendChild(sex);
        XmlNode age = xmlDoc.CreateElement("Age");
        age.InnerText = tBAge.Text;
        student.AppendChild(age);
        XmlNode picture = xmlDoc.CreateElement("Picture");
        picture.InnerText = tBPicture.Text;
        student.AppendChild(picture);


        xmlDoc.DocumentElement.AppendChild(student);
        xmlDoc.Save(ConfigurationManager.AppSettings.Get("studentFile"));
    }

Upvotes: 1

Views: 146

Answers (2)

Gauravsa
Gauravsa

Reputation: 6514

With LinqtoXml, this is fairly easy to do. Its strongly recommended to use Linq To XmL:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/adding-elements-attributes-and-nodes-to-an-xml-tree

try
{
    XDocument xmlDoc = XDocument.Load("StudentDoc.xml"));
    xmlDoc.Element("Students").Add(
    new XElement("Student", 
    new XElement("Name", "Peter"),
    new XElement("Grade", 10.0), 
    new XElement("Sex", "Male")));

    xmlDoc.Save("StudentDoc.xml"));
}
catch{}

You can then do different things like maybe sorting:

IEnumerable<decimal> names =  
    from student in root.Elements("Students")  
    orderby student.Name  
    select student.Name;  
foreach (string name in names)  
    Console.WriteLine(name);  

Upvotes: 1

peeyush singh
peeyush singh

Reputation: 1407

You can find the "Students" node

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ConfigurationManager.AppSettings.Get("studentFile"));
XmlElement root = xmlDoc.DocumentElement;
XmlNode node = root.SelectSingleNode("//Classrooms/Classroom/Students");

Then at the end you can append the new node to this one

node.AppendChild(student);
//xmlDoc.DocumentElement.AppendChild(student);
xmlDoc.Save(ConfigurationManager.AppSettings.Get("studentFile"));

Upvotes: 1

Related Questions