Skip to content

Commit

Permalink
Setting Document.setRootElement will clear other content besides the …
Browse files Browse the repository at this point in the history
…actual root element. Loop through content and just replace the root instead.
  • Loading branch information
Björn Ekryd committed May 24, 2022
1 parent d7bc52d commit fedc571
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
18 changes: 17 additions & 1 deletion sorter/src/main/java/sortpom/XmlProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,23 @@ public void sortXml() {
rootWrapper.sortStructureElements();
rootWrapper.connectXmlStructure();

newDocument.setRootElement(rootWrapper.getElementContent().getContent());
replaceRootElementInNewDocument(rootWrapper.getElementContent().getContent());
}

/** Setting root element directly on the document will clear other content */
private void replaceRootElementInNewDocument(Element newElement) {
var rootElement = newDocument.getRootElement();
var content = newDocument.content();

newDocument.clearContent();

for (var node : content) {
if (node == rootElement) {
newDocument.add(newElement);
} else {
newDocument.add(node);
}
}
}

public Document getNewDocument() {
Expand Down
10 changes: 10 additions & 0 deletions sorter/src/test/resources/MultilineComment_expected.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
base-parent
Copyright
All rights reserved.
Contributors:
Björn
-->
<?processing start?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<!-- The Basics
This is a multiline komment-->
<groupId>sortpom</groupId>
<artifactId>sortpom</artifactId>
</project>
<!-- End comment -->
<?processing end?>
12 changes: 11 additions & 1 deletion sorter/src/test/resources/MultilineComment_input.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
base-parent
Copyright
All rights reserved.
Contributors:
Björn
-->
<?processing start?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<artifactId>sortpom</artifactId>
<!-- The Basics
This is a multiline komment-->
<groupId>sortpom</groupId>
</project>
</project>
<!-- End comment -->
<?processing end?>

0 comments on commit fedc571

Please sign in to comment.