[Source: http://geekswithblogs.net/EltonStoneman]
The latest release of the OpenXML SDK (v2.0 September 2008 CTP) comes with the DocumentReflector tool which can load an OpenXML document and reverse engineer the code for generating that document with the SDK. It's very handy but there's an issue with it when you have a Word document with content parts that contain XML.
In this scenario, DocumentReflector will build the XML content for the part like this:
public static void GenerateCustomXmlPart1(OpenXmlPart part)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter(part.GetStream());
writer.Write("<?xml version=\"1.0\" encoding=\"utf-16\"?><RootNode></RootNode>");
writer.Flush();
writer.Close();
}
The problem is that the stream doesn't contain a Unicode byte mark, so if you generate a document with this and then try to open it in DocumentReflector, you'll get an error when you navigate to the content part: "There is no Unicode byte order mark. Cannot switch to Unicode". If you generate the whole document using DocumentReflector's code, you'll have the same issue with the core file properties, and the document won't open in Word.
It's a straightforward solution to use XmlWriter instead of StreamWriter:
public static void GenerateCustomXmlPart1(OpenXmlPart part)
{
XmlWriter writer = XmlWriter.Create(part.GetStream());
writer.WriteRaw("<RootNode></RootNode>");
writer.Flush();
writer.Close();
}
The created document will now have the Unicode byte mark in the content parts, and will load correctly in Word and in DocumentReflector. Note that you need to remove the opening <?xml…?> tag, as the XmlWriter adds this for you.