From 98d51e41398b658df158492a9b67a4b5d2ff2983 Mon Sep 17 00:00:00 2001 From: Bida Fan Date: Tue, 27 Dec 2022 07:49:35 +0000 Subject: Fix when bodyElements contain sdt, the inserted element is in the wrong position git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1906225 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/poi/xwpf/usermodel/XWPFDocument.java | 2 +- .../org/apache/poi/xwpf/usermodel/TestXWPFDocument.java | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java index af3a4d7beb..6ab0ae9907 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java @@ -842,7 +842,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { cursor.toCursor(newParaPos); while (cursor.toPrevSibling()) { o = cursor.getObject(); - if (o instanceof CTP || o instanceof CTTbl) { + if (o instanceof CTP || o instanceof CTTbl || o instanceof CTSdtBlock) { i++; } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java index 9756291e86..fe67289913 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java @@ -464,6 +464,22 @@ public final class TestXWPFDocument { } } + @Test + void testInsertNewParagraphWithSdt() throws IOException { + try (XWPFDocument doc = new XWPFDocument()) { + doc.createTOC(); + doc.createParagraph(); + try (XWPFDocument docx = XWPFTestDataSamples.writeOutAndReadBack(doc)) { + XWPFParagraph paragraph = docx.getParagraphArray(0); + XmlCursor xmlCursor = paragraph.getCTP().newCursor(); + XWPFParagraph insertNewParagraph = docx.insertNewParagraph(xmlCursor); + + assertEquals(insertNewParagraph, docx.getParagraphs().get(0)); + assertEquals(insertNewParagraph, docx.getBodyElements().get(1)); + } + } + } + @Test @Disabled("XWPF should be able to write to a new Stream when opened Read-Only") void testWriteFromReadOnlyOPC() throws Exception { -- cgit v1.2.3