0

I'm attempting to serialize XML and create a file. I'm serializing from an object that was auto generated from XSD using xsd.exe. The file processes and is created just fine. But whenever I run it against a validation tool I get an error Content Not Allowed In Prolog

My guess is that there are some malformed chars before the xml declaration, but I cannot seem them or see any bytes there. Here is my code that serializes and creates the XML document:

XmlSerializer ser = new XmlSerializer(typeof(ContinuityOfCareRecord));
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8,
                ConformanceLevel = ConformanceLevel.Document,
                OmitXmlDeclaration = false,
                Indent = true,
                NewLineChars = "\n",
                CloseOutput = true,
                NewLineHandling = NewLineHandling.Replace,
                CheckCharacters = true
            };
using (XmlWriter myWriter = XmlWriter.Create(ms, settings))
            {
                myWriter.Flush();
                //myWriter.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"ccr.xsl\"");
                ser.Serialize(myWriter, myCCR);
            }

Seems pretty simple, but if there are malformed characters at the beginning of the output XML file, how do I go about removing the characters?

The XML Document begins as so:

<?xml version="1.0" encoding="utf-8"?> <ContinuityOfCareRecord xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:astm-org:CCR"> <CCRDocumentObjectID>testccr</CCRDocumentObjectID> <Language>

Looks correct, but the validator just doesn't like it. I've been pounding my head on the desk all day about this so any sample code would be very helpful!

Thanks

Encryption
  • 1,809
  • 9
  • 37
  • 52
  • what validation tool are you running against? And can you deserialize the XML back to an object within C# without an error? – DiskJunky Mar 01 '13 at 23:39

1 Answers1

0

Looks like a problem with a BOM character, writing the code in this way can help:

using (XmlTextWriter myWriter = new XmlTextWriter(ms, new System.Text.UTF8Encoding(false)))
        {
            myWriter.Flush();
            //myWriter.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"ccr.xsl\"");
            ser.Serialize(myWriter, myCCR);
        }

This will remove the BOM character and the file will be encoded in UTF-8 Without BOM.

Jav_1
  • 462
  • 5
  • 12
  • Did I miss something? I thought you couldn't create an instance of XMLWriter. I'm actually getting an error on that line.. – Encryption Mar 01 '13 at 23:49