I'm trying to convert xml formatted with tags to a DOCX file. I'm not generating a new document, but inserting text in a template document.
<p id="_fab91699-6d85-4ce5-b0b5-a17197520a7f">This document is amongst a series of International Standards dealing with the conversion of systems of writing produced by Technical Committee ISO/TC 46, <em>Information and documentation</em>, WG 3 <em>Conversion of written languages</em>.</p>
I collected the text fragments in an array, then tried to process them with code like this:
foreach (var bkmkStart in wordDoc.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
{
if (bkmkStart.Name == "ForewordText")
{
forewordbkmkParent = bkmkStart.Parent;
for (var y = 0; y <= ForewordArray.Length / (double)2 - 1; y++)
{
if (ForewordArray[0, y] == "Normal")
{
if (y < ForewordArray.Length / (double)2 - 1)
{
if (ForewordArray[0, y + 1] == "Normal")
{
forewordbkmkParent.InsertBeforeSelf(new Paragraph(new Run(new Text(ForewordArray[1, y]))));
}
else
{
fPara = forewordbkmkParent.InsertBeforeSelf(new Paragraph(new Run(new Text(ForewordArray[1, y]))));
}
}
else
{
fPara.InsertAfter(new Run(new Text(ForewordArray[1, y])), fPara.GetFirstChild<Run>());
}
}
else
{
NewRun = forewordbkmkParent.InsertBeforeSelf(new Run());
NewRunProps = new RunProperties();
NewRunProps.AppendChild<Italic>(new Italic());
NewRun.AppendChild<RunProperties>(NewRunProps);
NewRun.AppendChild(new Text(ForewordArray[1, y]));
}
}
}
}
but I end up with malformed XML because the runs are inserted after the paragraphs instead of inside them:
<w:p>
<w:r>
<w:t>This document is amongst a series of International Standards dealing with the conversion of systems of writing produced by Technical Committee ISO/TC 46, </w:t>
</w:r>
</w:p>
<w:r>
<w:rPr>
<w:i />
</w:rPr>
<w:t>Information and documentation</w:t>
</w:r>
<w:p>
<w:r>
<w:t>, WG 3 </w:t>
</w:r>
<w:r>
<w:t>.</w:t>
</w:r>
</w:p>
<w:r>
<w:rPr>
<w:i />
</w:rPr>
<w:t>Conversion of written languages</w:t>
</w:r>
Doing this the right way, using the SDK, would be best. As an alternative, I was able to create a string with all the correct XML and text using regexes, but I can't find a WordprocessingDocument method to turn that into an XML fragment that I can insert.