Duplicated root when serializing



I am trying to serialize a dictionary into xml, but the structure of the xml is different to the one I would like. For some reason instead of having one root and multiple child within that root I get a new root for each key and value in the dictionary. Also the message box is being shown for each KeyValuePair within the dictionary, I would like the message box to be shown once when the dictionaries were exported. I am using Microsoft Visual Studio 2010 with C# and all values within the dictionary collected from text boxes on a windows form.


This is how the current xml layout looks like:



<?xml version="1.0" encoding="utf-8"?>
<Coordinate xmlns:xsi="http://ift.tt/ra1lAU" xmlns:xsd="http://ift.tt/tphNwY">
<Date_Time>10/02/2015 11/17/00</Date_Time>
<BeaconID>1</BeaconID>
<X_Coordinate>2</X_Coordinate>
<Y_Coordinate>3</Y_Coordinate>
</Coordinate><?xml version="1.0" encoding="utf-8"?>
<Coordinate xmlns:xsi="http://ift.tt/ra1lAU" xmlns:xsd="http://ift.tt/tphNwY">
<Date_Time>10/02/2015 11/17/01</Date_Time>
<BeaconID>2</BeaconID>
<X_Coordinate>3</X_Coordinate>
<Y_Coordinate>4</Y_Coordinate>
</Coordinate>


And this is how I would like it to look:



<?xml version="1.0" encoding="utf-8"?>
<Coordinates xmlns:xsi="http://ift.tt/ra1lAU" xmlns:xsd="http://ift.tt/tphNwY">
<Coordinate>
<Date_Time>10/02/2015 11/17/00</Date_Time>
<BeaconID>1</BeaconID>
<X_Coordinate>2</X_Coordinate>
<Y_Coordinate>3</Y_Coordinate>
</Coordinate>
<Coordinate>
<Date_Time>10/02/2015 11/17/01</Date_Time>
<BeaconID>2</BeaconID>
<X_Coordinate>3</X_Coordinate>
<Y_Coordinate>4</Y_Coordinate>
</Coordinate>
</Coordinates>


This is all of my xml related code:



public void btn_Submit_Click(object sender, EventArgs e)
{
foreach (KeyValuePair<string, Tuple<int, int>> entry in d)
{
Coordinate v = new Coordinate();

v.Date_Time = DateTime.Now.ToString("dd/MM/yyyy hh/mm/ss");
v.BeaconID = entry.Key;
v.X_Coordinate = entry.Value.Item1.ToString();
v.Y_Coordinate = entry.Value.Item2.ToString();

SaveValues(v);
}
}

public class Coordinate//Root element
{
public string Date_Time { get; set; }
public string BeaconID { get; set; }
public string X_Coordinate { get; set; }
public string Y_Coordinate { get; set; }
}

public void SaveValues(Coordinate v)
{
XmlSerializer serializer = new XmlSerializer(typeof(Coordinate));
using (TextWriter textWriter = new StreamWriter(@"F:\Vista\Exporting into XML\Test1\Coordinates output.xml", true))
{
serializer.Serialize(textWriter, v);
}
MessageBox.Show("Coordinates were exported successfully", "Message");//Let the user know the export was succesfull
}


Can you tell me what I am doing wrong. If I am missing anything or I just wasn't clear enough just let me know it and I will help with it. I am new to XML and to serialization so any help would be appreciated.


No comments:

Post a Comment