我将MS word doc保存为.docx
。我想通过编辑docx的XML文件在我的文本中插入新行。我已经尝试过

,
,
,	
,而且它总是只给我空间而不是新行。
它的作用:
(XML代码)
<w:t>hel
lo</w:t>
当我打开.docx
文件时,它会更改为:
Hel lo
并不是因为我希望在一行上Hel
而在第二行上lo
。
答案 0 :(得分:29)
使用<w:br/>
标记。
我通过创建Word文档,将其保存为XML(通过“另存为”),使用Shift Enter添加强制换行符并检出更改来找到它。基本差异似乎只是w:br
标记,显然反映了HTML br
标记。
答案 1 :(得分:2)
如果它对任何人有帮助,下面的c#代码将创建多行XML结构
//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;
}
}
上面的代码将创建必要的子节点和回车符,并且还会处理前缀。
答案 2 :(得分:0)
基于@Lenny上面的回答,这是在Mac上使用MS Word 2011的情况下使用Obj-C的方法:
- (NSString *)setWordXMLText:(NSString *)str
{
NSString *newStr = @"";
// split the string into individual lines
NSArray *lines = [str componentsSeparatedByString: @"\n"];
if (lines.count > 1)
{
// add XML nodes for each line so that Word XML will accept the new lines
for (int count = 0; count < lines.count; count++)
{
newStr = [newStr stringByAppendingFormat:@"<w:t>%@</w:t>", lines[count]];
// Not the last line? add a line break
if (count != lines.count - 1)
{
newStr = [newStr stringByAppendingString:@"<w:br/>"];
}
}
return newStr;
}
else
{
return str;
}
}