I’m trying to move a ranged sdt (with id -653446606) before another sdt (with id 1766038418) with the following code on the attached file.
private void moveRangedSdtTest() throws Exception {
// Load the document
Document doc =
new Document("C:\\temp_doc\\01 - Konzernlagebericht.docx");
// Find the StructuredDocumentTagRangeStart (ranged SDT start)
// Iterate through all StructuredDocumentTagRangeStart nodes in the document
NodeCollection<Node> sdtRangeStarts = doc.getChildNodes(NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_START, true);
StructuredDocumentTagRangeStart rangeStart = null;
for (Node node : sdtRangeStarts) {
StructuredDocumentTagRangeStart currentRangeStart = (StructuredDocumentTagRangeStart) node;
// Check if the current node's ID matches the target ID
if (currentRangeStart.getId() == -653446606) {
rangeStart = currentRangeStart;
break;
}
}
StructuredDocumentTagRangeEnd rangeEnd = rangeStart.getRangeEnd();
sdtRangeStarts = doc.getChildNodes(NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_START, true);
StructuredDocumentTagRangeStart normalSdt = null;
for (Node node : sdtRangeStarts) {
StructuredDocumentTagRangeStart currentRangeStart = (StructuredDocumentTagRangeStart) node;
// Check if the current node's ID matches the target ID
if (currentRangeStart.getId() == 1766038418) {
normalSdt = currentRangeStart;
break;
}
}
if (rangeStart != null && rangeEnd != null && normalSdt != null) {
// Collect all nodes between rangeStart and rangeEnd, inclusive
List<Node> nodesToMove = new LinkedList<>();
Node currentNode = rangeStart;
while (currentNode != null) {
nodesToMove.add(currentNode);
if (currentNode.equals(rangeEnd)) {
break;
}
currentNode = currentNode.getNextSibling();
}
// Insert the collected nodes before the normal SDT
for (Node node : nodesToMove) {
normalSdt.getParentNode().insertBefore(node.deepClone(true), normalSdt);
}
// Remove the original nodes
for (Node node : nodesToMove) {
node.remove();
}
}
// Save the modified document
doc.save("C:\\temp_doc\\01 - Konzernlagebericht_moved.docx");
}
The result is not as expected. This will move the content control but then the others will be included in it. What am I doing wrong.
Thanks in advance.
01 - Konzernlagebericht.docx (189,8 KB)