我正在尝试使用 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/