adding duplicate element inside an xml file



I have this xmlfile :



<root>
<Friend_2>
<MESSAGE_BODY>hi</MESSAGE_BODY>
<MESSAGE_SENDER_ID>1</MESSAGE_SENDER_ID>
<MESSAGE_RECEIVER_ID>2</MESSAGE_RECEIVER_ID>
<MESSAGE_CREATION_DATE>2014-08-29T15:33:18.1191004+03:00</MESSAGE_CREATION_DATE>
</Friend_2>
</root>


i am using this function to add elements to this file by doing this :



private void createNode(string body, string senderid, string receiverid,DateTime creationDate,string path1,string path2)
{
XDocument doc1 = XDocument.Load(path1);
XDocument doc2 = XDocument.Load(path2);
XElement root1 = new XElement("Friend_"+receiverid);
XElement root2 = new XElement("Friend_"+senderid);

root1.Add(new XElement("MESSAGE_BODY", body));
root1.Add(new XElement("MESSAGE_SENDER_ID", senderid));
root1.Add(new XElement("MESSAGE_RECEIVER_ID", receiverid));
root1.Add(new XElement("MESSAGE_CREATION_DATE", creationDate));


root2.Add(new XElement("MESSAGE_BODY", body));
root2.Add(new XElement("MESSAGE_SENDER_ID", senderid));
root2.Add(new XElement("MESSAGE_RECEIVER_ID", receiverid));
root2.Add(new XElement("MESSAGE_CREATION_DATE", creationDate));

if (doc1.Root.Element(root1.Name.LocalName) == null)
{
doc1.Element("root").Add(root1);
}
if (doc2.Root.Element(root2.Name.LocalName) == null)
{
doc2.Element("root").Add(root2);
}
doc1.Save(path1);
doc2.Save(path2);
}


but the original element are being replaced i want my xml file to look like this :



<root>
<Friend_2>
<MESSAGE_BODY>hi</MESSAGE_BODY>
<MESSAGE_SENDER_ID>1</MESSAGE_SENDER_ID>
<MESSAGE_RECEIVER_ID>2</MESSAGE_RECEIVER_ID>
<MESSAGE_CREATION_DATE>2014-08-29T15:33:18.1191004+03:00</MESSAGE_CREATION_DATE>
<MESSAGE_BODY>how r you ?</MESSAGE_BODY>
<MESSAGE_SENDER_ID>1</MESSAGE_SENDER_ID>
<MESSAGE_RECEIVER_ID>2</MESSAGE_RECEIVER_ID>
<MESSAGE_CREATION_DATE>2014-10-29T15:33:18.1191004+03:00</MESSAGE_CREATION_DATE>
</Friend_2>
</root>


my main reason to have this schema is because i am using a function that parse the document and return a dataTable containing 4 columns and 2 rows



public static DataSet ConvertXMLToDataTable(string xmlString)
{
DataSet dataset = new DataSet();
dataset.ReadXml(xmlString);
return dataset.Tables.Count > 0 ? dataset : null;
}
DataSet Chat_ds=Convertor.ConvertXMLToDataTable(path);
if (Chat_ds.Tables.Count > 0)
{
DataTable Chat_dt = Chat_ds.Tables["Friend_" + FriendID];
...................

No comments:

Post a Comment