Search code examples
c#xmlopenxmlopenxml-sdkwordprocessingml

Line Breaks In CustomXMLPart


I'm updating a word document by rewriting the CustomXMLPart file. I've basically followed this tutorial: http://blogs.msdn.com/b/brian_jones/archive/2009/01/05/taking-advantage-of-bound-content-controls.aspx

private bool _makeDoc()
        {

        var path = HttpContext.Current.Server.MapPath("~/Classes/Word/template.docx");
        using (WordprocessingDocument myDoc = WordprocessingDocument.Open(path, true))
        {
            //create new XML string
            //these values will populate the template word doc
            string newXML = "<root>";
                newXML += "<name>";
                newXML += "name goes here";
                newXML += "</name>";
                newXML += "<bio>";
                newXML += "text" + "more text";
                newXML += "</bio>";
            newXML += "</root>";

            MainDocumentPart mainPart = myDoc.MainDocumentPart;

            //delete old xml part
            mainPart.DeleteParts<CustomXmlPart>(mainPart.CustomXmlParts);

            //add new xml part
            CustomXmlPart customXml = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
            using(StreamWriter ts = new StreamWriter(customXml.GetStream()))
            {
                ts.Write(newXML);
            }
            myDoc.Close();
        }
        return true;
    }

The problem is that I can't figure out how to add a line break between "text" and "more text". I've tried Environment.NewLine, I've tried wrapping it in <w:p><w:r><w:t> tags. I can't seem to get it to produce a valid docx file.

Any help would be appreciated.


Solution

  • The Content Control properties has an option for "Allow carriage returns". Turning this on, and using Environment.NewLine worked perfectly.