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

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

问题描述

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

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() 是真的,np.getText()> 为空白,而 <​​code>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天全站免登陆