10

MS word doc を として保存してい.docxます。docx の XML ファイルを編集して、テキストに改行を挿入したいと考えています。

、を既に試しましたが、	改行ではなくスペースのみが常に与えられます。

それは何をします:

(XML コード) <w:t>hel&#xA;lo</w:t>

.docxファイルを開くと、次のように変更されます。

Hel loHel1行目と2行目に行きたかったわけではありませんlo

4

3 に答える 3

30

<w:br/>タグを使用します。

Word 文書を作成し、それを XML として保存し (名前を付けて保存)、Shift Enter で強制的に改行を追加し、変更をチェックアウトして見つけました。本質的な違いはw:brタグだけのようで、明らかに HTML タグを反映していますbr

于 2012-11-07T13:55:59.000 に答える
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;
    }
}

上記のコードは、必要な子ノードと改行を作成し、プレフィックスも処理します。

于 2015-01-16T12:23:06.077 に答える