Reputation: 361
I've been working on a map editor for a tile based game. I want to load and save maps to an xml file.
Found out about the xmlSerializer class and wanted to give it a try instead of building my own parser. It wasn't too hard to figure out. The one problem I'm having right now is that I cannot get rid of the xml declaration. It seems like the XmlSettings are not being applied at all. Been messing around with it all night with no progress, help is greatly appreciated. Here is the code:
public static void SerializeMap(Array map)
{
XmlWriterSettings xmlSettings = new XmlWriterSettings();
xmlSettings.OmitXmlDeclaration = true;
xmlSettings.ConformanceLevel = ConformanceLevel.Fragment;
xmlSettings.Indent = false;
var xmlSerializer = new XmlSerializer(typeof(Tile));
XmlSerializerNamespaces emptyNameSpace = new XmlSerializerNamespaces();
emptyNameSpace.Add("", "");
//create string of xml first, then write to file
StringWriter stringWriter = new StringWriter();
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlSettings))
{
for (int z = 0; z < map.GetLength(0); z++)
{
for (int x = 0; x < map.GetLength(1); x++)
{
for (int y = 0; y < map.GetLength(2); y++)
{
xmlSerializer.Serialize(stringWriter, map.GetValue(z, x, y), emptyNameSpace);
}
}
}
}
FileStream fs = new FileStream("Content/tiletest.xml", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(xmlText);
sw.Close();
fs.Close();
}
Because I'm looping through the objects, each new written object in the xml file will have an xml declaration attached, which will break the xml formatting. Incredibly annoying because everything else works fine with the serialization.
Upvotes: 3
Views: 1793
Reputation: 21
You are passing XmlWriterSettings structure to XmlWriter, but you are not using XmlWriter instance anywhere. To fix the issue change
xmlSerializer.Serialize(stringWriter, map.GetValue(z, x, y), emptyNameSpace);
to
xmlSerializer.Serialize(xmlWriter, map.GetValue(z, x, y), emptyNameSpace);
Upvotes: 2
Reputation: 47789
yes unfortunately the XmlSerializer unfortunately isn't too consistent, in particular between windows and xbox. Here's a thought, use the built in XnaContent serializer. Here's a great tutorial that goes over it:
http://glennwatson.net/?p=143
Or the documentation from Microsoft: http://msdn.microsoft.com/en-us/library/ff604981.aspx
note: the community content on the msdn page linked above references Shawn Hargreave's excellent blog posts on the topic as well:
Upvotes: 0