Подтвердить что ты не робот

XML - добавление новой строки

У меня MS Word doc сохранен как .docx. Я хочу вставить новую строку в свой текст, поместив XML файл docx. Я уже пробовал 
, 
, 
, 	, amd всегда дает мне только пробел, а не новую строку.

что он делает:

(XML-код) <w:t>hel&#xA;lo</w:t>

Когда я открываю файл .docx, он изменяется на:

Hel lo не так, как я хотел быть Hel на одной строке и lo на секущей строке.

4b9b3361

Ответ 1

Используйте тег <w:br/>.

Я нашел его, создав документ Word, сохранив его как XML (через Save As), добавив принудительный разрыв строки с помощью Shift Enter и проверив изменение. Существенным отличием, по-видимому, является тег w:br, который, по-видимому, отражает тег HTML br.

Ответ 2

В случае, если это кому-то поможет, следующий бит кода С# создаст многострочную структуру 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;
    }
}

Приведенный выше код создаст необходимые дочерние узлы и возвращает каретки, а также сохранит префикс.

Ответ 3

Основываясь на ответе @Lenny выше, это то, что работает с Obj-C в моей ситуации с MS Word 2011 на Mac:

- (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;
    }
}