0

I am serialising a number of classes to an XML file using the following code

static void GetFromDBToXml()
    {
        var thejob = Xmltodb.Singleton.DBManager.GetSingleObject<job>("jobid", JobData.Job.Jobid);
        var theparts = Xmltodb.Singleton.DBManager.GetListOfObjects<parts>("jobid", JobData.Job.Jobid);
        var thesurv = Xmltodb.Singleton.DBManager.GetListOfObjects<jobsurvey>("jobid", JobData.Job.Jobid);

        try
        {
            using (var fs = new FileStream(Path.Combine(Xmltodb.Singleton.ContentDirectory, "temp.xml"), FileMode.OpenOrCreate))
            {
                var xmlSerializer = new XmlSerializer(typeof(job));
                xmlSerializer.Serialize(fs, thejob);
                xmlSerializer = new XmlSerializer(typeof(parts));
                foreach (var p in theparts)
                    xmlSerializer.Serialize(fs, p);
                xmlSerializer = new XmlSerializer(typeof(jobsurvey));
                foreach (var s in thesurv)
                    xmlSerializer.Serialize(fs, s);
            }
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Can't write the xml file : {0}--{1}", ex.Message, ex.StackTrace);
        }
    }

The code is being drawn directly from SQLite and written to an XML file.

While this works, at the end of each class and start of the next I'm getting the XML header added each time. In other words

</jobsurvey>
<?xml version="1.0" encoding="utf-8">
<parts xmlns:xsi="http://www.w3.org ...

Is there a way to prevent the serialiser from generating the <?xml and xmlns: parts for each class being serialised without having to create the file, then reparse to remove these bits I don't need?

Nodoid
  • 1,449
  • 3
  • 24
  • 42
  • 1
    You should be outputting valid xml. Valid xml has an xml version at the top, and only one root element. You're violating both. The solution, normally, is to create a type that represents the root of your xml, add a property for each of your job, parts and jobsurvey, set them and then serialize this instance. –  Apr 21 '15 at 16:47
  • Use OmitXmlDeclarations =true for your settings as in http://stackoverflow.com/questions/1772004/how-can-i-make-the-xmlserializer-only-serialize-plain-xml – ares777 Apr 21 '15 at 16:51

1 Answers1

0

You can try something like this. The important things here are XMLWriterSettings and XmlSerializerNamespaces.

XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;

MemoryStream ms = new MemoryStream();
XmlWriter writer = XmlWriter.Create(ms, settings);

XmlSerializerNamespaces names = new XmlSerializerNamespaces();
names.Add("", "");

XmlSerializer cs = new XmlSerializer(typeof(Cat));

cs.Serialize(writer, new Cat { Lives = 9 }, names);

ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
var xml = sr.ReadToEnd();
Legends
  • 21,202
  • 16
  • 97
  • 123