Hi Nitesh,
I am providing my solution based on C file pointer approach in C#.
Logic:
1) Open the file in a stream.
2) Move the file pointer to the last employee node.
3) Add a new node there.
First two points are accomplished here:
FileStream FStream = new FileStream("Employee.xml", FileMode.Open);
byte[] ReadAByte = new byte[1];
int FilePointerOffset = 0;
while (FilePointerOffset < FStream.Length - 25)
{
FStream.Read(ReadAByte, 0, 1);
FilePointerOffset++;
}
We are moving the file pointer to 25 characters ahead of the EOF as that is the point where we want to insert a new employee record. The ending nodes "</employees></company>" are 25 characters long including newlines. So before that point we are inserting the new employee.
The third point is accomplished here:
byte[] WriteSomeBytes = new byte[200];
WriteSomeBytes = Encoding.ASCII.GetBytes("\t\t<employee>" + Environment.NewLine +
"\t\t\t<id>300</id>" + Environment.NewLine +
"\t\t\t<name>sa</name>" + Environment.NewLine +
"\t\t</employee>" + Environment.NewLine +
"\t</employees>" + Environment.NewLine +
"</company>");
FStream.Write(WriteSomeBytes, 0, WriteSomeBytes.Length);
FStream.Close();
Please note that you also need to include the ending nodes here as this part will merely discard anything from the point of inserting. Please modify the values of the employee id and name accordingly.
As an alternate to reading byte by byte, you can directly move to the point of inserting. So in lieu of the above code the following code works the same:
FileStream FStream = new FileStream("Employee.xml", FileMode.Open);
byte[] ReadBytes = new byte[FStream.Length - 25];
FStream.Read(ReadBytes, 0, (int)FStream.Length - 25);
byte[] WriteSomeBytes = new byte[200];
WriteSomeBytes = Encoding.ASCII.GetBytes("\t\t<employee>" + Environment.NewLine +
"\t\t\t<id>22200</id>" + Environment.NewLine +
"\t\t\t<name>sa</name>" + Environment.NewLine +
"\t\t</employee>" + Environment.NewLine +
"\t</employees>" + Environment.NewLine +
"</company>");
FStream.Write(WriteSomeBytes, 0, WriteSomeBytes.Length);
FStream.Close();
The problem is the file size; as you mentioned it is a pretty big file, so it might use up a huge space. Please try both approaches and see the effect.
Finally, don't forget to keep a backup of the XML file before applying this code.