Add getter for body elements in XWPFSDTContent. (#991)

* Add getter for body elements in XWPFSDTContent.

This getter allows to navigate the POI objects stored inside a
XWPFSDTContent object without resorting to navigating XML.

* Address comments in review.
This commit is contained in:
Jacobo Aragunde Pérez 2026-01-09 13:28:30 +01:00 committed by GitHub
parent aead782eb2
commit 6670c48c30
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 33 additions and 0 deletions

View File

@ -17,6 +17,7 @@
package org.apache.poi.xwpf.usermodel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.poi.util.Beta;
@ -107,6 +108,15 @@ public class XWPFSDTContent implements ISDTContent {
}
}
/**
* Get the body elements inside this SDT content element.
* @return Unmodifiable list containing body elements.
* @since 6.0.0
*/
public List<ISDTContents> getBodyElements() {
return Collections.unmodifiableList(bodyElements);
}
@Override
public String getText() {
StringBuilder text = new StringBuilder();

View File

@ -95,6 +95,29 @@ public final class TestXWPFSDT {
}
}
@Test
void testGetSDTContentBodyElements() throws Exception {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx")) {
IBodyElement sdtBodyElement = doc.getBodyElements().get(2);
assertTrue(sdtBodyElement instanceof XWPFSDT, "sdtBodyElement instance of XWPFSDT");
XWPFSDTContent content = (XWPFSDTContent) ((XWPFSDT) sdtBodyElement).getContent();
assertEquals(3, content.getBodyElements().size(), "elements inside SDT");
ISDTContents c1 = content.getBodyElements().get(0);
assertTrue(c1 instanceof XWPFParagraph, "c1 instance of XWPFParagraph");
assertEquals("Rich_text_pre_table", ((XWPFParagraph) c1).getText());
ISDTContents c2 = content.getBodyElements().get(1);
assertTrue(c2 instanceof XWPFTable, "c2 instance of XWPFTable");
assertEquals(3, ((XWPFTable) c2).getNumberOfRows(), "rows in table inside SDT");
assertEquals("Rich_text_cell1", ((XWPFTable) c2).getRow(0).getCell(0).getText());
ISDTContents c3 = content.getBodyElements().get(2);
assertTrue(c3 instanceof XWPFParagraph, "c3 instance of XWPFParagraph");
assertEquals("Rich_text_post_table", ((XWPFParagraph) c3).getText());
}
}
/**
* POI-54771 and TIKA-1317
*/