java - Docx4j:在父级下的当前项目之后插入项目 X 次

标签 java insert ms-word docx4j

我正在尝试使用 DOCX4J 解析内容并将其插入模板中。作为此模板的一部分,我有循环,我需要复制两个标记之间的所有内容,并重复所有内容 X 次。

相关代码如下:

public List<Object> getBetweenLoop(String name){
        String startTag = this.tag_start + name + "_LOOP" + this.tag_end;
        String endTag = this.tag_start + name + this.tag_end;
        P begin_loop = this.getTagParagraph(startTag);
        P end_loop = this.getTagParagraph(endTag);

        ContentAccessor parent = (ContentAccessor) this.getCommonParent(begin_loop, end_loop);

        List<Object> loop = new ArrayList<Object>();

        boolean save = false;
        //Cycle through the content for the parent and copy all the objects that
        //are between and including the start and end-tags
        for(Object item : parent.getContent()){
            if(item.equals(begin_loop) || item.equals(end_loop))
                save = (save) ? false : true;
            if(save || item.equals(end_loop)){
                loop.add(XmlUtils.deepCopy(item));
            }
            if(item.equals(end_loop)){
                //Here I want to insert everything copied X times after the current item and then exit the for loop.
                //This is the part I'm not sure how to do since I don't see any methods "Insert Child", etc.
            }
        }
        return loop;
    }

getTagParagraph 成功返回表示所发送标记的段落的对象。这工作得很漂亮。

getCommonParent 返回两个提供的标记之间的共享父级。这工作得很漂亮。

正如评论所述,我的问题是如何将新复制的项目插入到适当的位置。

最佳答案

如果您希望插入存储在 loop 集合中的所有对象,您只需执行以下操作(在您评论的条件中):

item.getContent().addAll(loop);

item 表示 end_loop 对象(段落或其他内容),并将您收集的所有对象插入到 loop 集合中。 (addAll 也可能需要一个 int 参数,我不记得了,但如果它确实需要,那么这就是整个 MainDocumentPart.getContent() JAXB 文档表示中所需的索引) .

关于java - Docx4j:在父级下的当前项目之后插入项目 X 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17078280/

相关文章:

java - 使用递归解决二进制间隙

java - 使用 for 循环从 ArrayList 中获取 Drawable[]

java - BigQueryIO 读取获取 TableSchema

sql-server - 如何在 Orchard 中使用带有 int key (NOT IDENTITY) 的 IRepository

php - 插入行后如何从 MySQL 表返回值?

ms-word - 将 Office JS 页面中的拖放到 Word 文档中

c# - 使用 OpenXml 调用 AddAlternativeFormatImportPart 后文档损坏

java - 类型不兼容和 System.out.print 错误?

SQL Access INSERT INTO 失败

vba - 在Word中删除页面