复制包括所有内容和属性的段落的精确副本吗? [英] Make an exact copy of a paragraph including all contents and properties?

查看:82
本文介绍了复制包括所有内容和属性的段落的精确副本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个段落准确复制到另一个段落中(我正在将模板复制到新文档中以进行单词替换).我正在为表格单元格中的段落执行此操作,但我认为这并不重要.以下代码几乎可以正常工作:

I'm trying to do an exact copy of one paragraph into another (I'm copying a template over to a new document for word-replacement). I'm doing this for paragraphs within a table cell, but I don't believe that is significant. The following code nearly works:

for (XWPFParagraph p : cell.getParagraphs()) {
    XWPFParagraph np = newCell.addParagraph();
    np.getCTP().set(p.getCTP());
}

问题是,当np.getCTP().xmlText().equals(p.getCTP().xmlTest()为true时,np.getText()为空白,而p.getText()具有该段落的内容.似乎我的段落不了解我对XML所做的基础更改.这会导致我的输出文档包含占位符文本,因为我的代码似乎再也看不到该段落的内容才能执行替换.

The problem is, while np.getCTP().xmlText().equals(p.getCTP().xmlTest() is true, np.getText() is blank while p.getText() has the contents of the paragraph. It seems like my paragraph doesn't know about the underlying change I made to the XML. This results in my output document containing the placeholder text because my code can't seem to see the contents of the paragraph any more in order to perform the replacement.

如何完美复制包含所有内容和属性的段落?

How can I make a perfect copy of a paragraph including all contents and properties?

推荐答案

这似乎可以完成工作.我不确定整个cloneRun()方法是否不能由nr.getCTR().set(r.getCTR());代替,但这似乎比后悔更安全.

This seems to be getting the job done. I'm not sure that the whole cloneRun() method couldn't be replaced by nr.getCTR().set(r.getCTR()); but this seems better safe than sorry.

public static void cloneParagraph(XWPFParagraph clone, XWPFParagraph source) {
    CTPPr pPr = clone.getCTP().isSetPPr() ? clone.getCTP().getPPr() : clone.getCTP().addNewPPr();
    pPr.set(source.getCTP().getPPr());
    for (XWPFRun r : source.getRuns()) {
        XWPFRun nr = clone.createRun();
        cloneRun(nr, r);
    }
}

public static void cloneRun(XWPFRun clone, XWPFRun source) {
    CTRPr rPr = clone.getCTR().isSetRPr() ? clone.getCTR().getRPr() : clone.getCTR().addNewRPr();
    rPr.set(source.getCTR().getRPr());
    clone.setText(source.getText(0));
}

这篇关于复制包括所有内容和属性的段落的精确副本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆