XML - adding new line
Solution 1
Use the <w:br/>
tag.
I found it by creating a Word document, saving it as XML (via Save As), adding a forced line break with Shift Enter, and checked out the change. The essential difference seems to be just the w:br
tag, apparently reflecting the HTML br
tag.
Solution 2
In case it helps anyone, the following bit of c# code will create the multi-line XML structure
//Sets the text for a Word XML <w:t> node
//If the text is multi-line, it replaces the single <w:t> node for multiple nodes
//Resulting in multiple Word XML lines
private static void SetWordXmlNodeText(XmlDocument xmlDocument, XmlNode node, string newText)
{
//Is the text a single line or multiple lines?>
if (newText.Contains(System.Environment.NewLine))
{
//The new text is a multi-line string, split it to individual lines
var lines = newText.Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
//And add XML nodes for each line so that Word XML will accept the new lines
var xmlBuilder = new StringBuilder();
for (int count = 0; count < lines.Length; count++)
{
//Ensure the "w" prefix is set correctly, otherwise docFrag.InnerXml will fail with exception
xmlBuilder.Append("<w:t xmlns:w=\"http://schemas.microsoft.com/office/word/2003/wordml\">");
xmlBuilder.Append(lines[count]);
xmlBuilder.Append("</w:t>");
//Not the last line? add line break
if (count != lines.Length - 1)
{
xmlBuilder.Append("<w:br xmlns:w=\"http://schemas.microsoft.com/office/word/2003/wordml\" />");
}
}
//Create the XML fragment with the new multiline structure
var docFrag = xmlDocument.CreateDocumentFragment();
docFrag.InnerXml = xmlBuilder.ToString();
node.ParentNode.AppendChild(docFrag);
//Remove the single line child node that was originally holding the single line text, only required if there was a node there to start with
node.ParentNode.RemoveChild(node);
}
else
{
//Text is not multi-line, let the existing node have the text
node.InnerText = newText;
}
}
The code above will create the necessary child nodes and carriage returns, and takes care of the prefix as well.
Mario LIPCIK
Updated on June 18, 2022Comments
-
Mario LIPCIK almost 2 years
I have MS word doc saved as
.docx
. I want to insert new line in my text by edditing XML file of docx. I have already tried

,
,
,	
, amd it always gives me only space not a new line.what it does:
(XML code)
<w:t>hel
lo</w:t>
When I open
.docx
file then it is changed to:Hel lo
not as I wanted to beHel
on one line andlo
on secound line. -
Vlad Dneprovskiy almost 11 yearsYou saved me a lot of time! Thx for answer!
-
Sebas almost 8 yearsMight seem obvious but what actually needs to be done is replacing the
<w:t></w:t>
tag all together with<w:br/>
...