### Basic Configuration Setup
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Initialize DomTrip with default configuration settings. This is a starting point for most use cases.
```java
DomTripConfig config = DomTripConfig.defaults();
```
--------------------------------
### Build and Install from Source (Local Build)
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/maven/installation.md
Steps to clone the DomTrip repository, build it locally using Maven wrapper, and install it.
```bash
git clone https://github.com/maveniverse/domtrip.git
cd domtrip
./mvnw clean install
```
--------------------------------
### Start DomTrip Website Development Server
Source: https://github.com/maveniverse/domtrip/blob/main/README.md
Start a development server for the DomTrip website documentation. Requires Node.js and npm.
```bash
cd website
npm install
npm start
```
--------------------------------
### Document Configuration Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Illustrates configuring document-level settings during the creation process.
```java
Editor.of("root", ns -> {
ns.element("child", "text");
}).withConfig(new DomTripConfig().setIndentation(" "));
```
--------------------------------
### XML Configuration Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/syntax-debug.html
This is an example of an XML structure, likely for configuration, showing nested elements and values.
```xml
localhost
5432
admin
secret
```
--------------------------------
### Quick XML Editing Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/introduction.md
A quick example demonstrating how to use DomTrip to edit an XML document, preserving original elements and formatting.
```java
{cdi:snippets.snippet('quick-example')}
```
--------------------------------
### Start development mode
Source: https://github.com/maveniverse/domtrip/blob/main/website/README.md
Launches the development server with hot reload capabilities for the website module.
```shell
cd website
../mvnw quarkus:dev
```
--------------------------------
### Complete Configuration Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Build a comprehensive DomTripConfig object by chaining multiple configuration methods for formatting, content preservation, and output settings.
```java
DomTripConfig config = DomTripConfig.defaults()
// Formatting settings
.withIndentString(" ") // 2-space indentation
.withPrettyPrint(false) // No reformatting
// Content preservation
.withCommentPreservation(true) // Keep comments
.withProcessingInstructionPreservation(true) // Keep PIs
// Quote and declaration settings
.withDefaultQuoteStyle(QuoteStyle.DOUBLE) // Double quotes for new attrs
.withXmlDeclaration(true) // Include XML declaration
// Line ending settings
.withLineEnding("\n"); // Unix line endings
```
--------------------------------
### Original XML Sample
Source: https://github.com/maveniverse/domtrip/blob/main/README.md
An example of an original XML file before editing with DomTrip.
```xml
com.example
my-app
1.0.0
```
--------------------------------
### Development Setup for DomTrip Maven Extension
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/maven/installation.md
Instructions for cloning the DomTrip repository and setting up for development, including building and importing into an IDE.
```bash
git clone https://github.com/maveniverse/domtrip.git
cd domtrip
./mvnw clean compile
# Import into your IDE as a Maven project
```
--------------------------------
### Spring Configuration
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Example demonstrating XML editing for Spring configuration files.
```java
{cdi:snippets.snippet('spring-configuration')}
```
--------------------------------
### Verify DomTrip Installation
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/getting-started/installation.md
A simple Java test to confirm DomTrip is correctly installed and functional.
```java
{cdi:snippets.snippet('installation-test')}
```
--------------------------------
### Use Fluent API for Document Setup
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/document.md
Configure document structure using a fluent interface.
```java
{cdi:snippets.snippet('fluent-api')}
```
--------------------------------
### Whitespace Configuration Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Configure how whitespace is handled during XML processing. This example shows enabling whitespace preservation.
```java
DomTripConfig config = DomTripConfig.defaults()
.withWhitespacePreservation(true);
```
--------------------------------
### Create Maven POM from Scratch
Source: https://github.com/maveniverse/domtrip/blob/main/maven/README.md
A complete example showing the initialization of a new POM document and the sequential addition of project metadata, properties, dependencies, and build plugins.
```java
// Create a new POM from scratch
PomEditor editor = new PomEditor();
editor.createMavenDocument("project");
Element root = editor.root();
// Add basic project information
editor.insertMavenElement(root, MODEL_VERSION, "4.0.0");
editor.insertMavenElement(root, GROUP_ID, "com.example");
editor.insertMavenElement(root, ARTIFACT_ID, "my-project");
editor.insertMavenElement(root, VERSION, "1.0.0");
editor.insertMavenElement(root, PACKAGING, "jar");
// Add project metadata
editor.insertMavenElement(root, NAME, "My Example Project");
editor.insertMavenElement(root, DESCRIPTION, "An example project");
// Add properties
Element properties = editor.insertMavenElement(root, PROPERTIES);
editor.addProperty(properties, "maven.compiler.source", "17");
editor.addProperty(properties, "maven.compiler.target", "17");
// Add dependencies
Element dependencies = editor.insertMavenElement(root, DEPENDENCIES);
editor.addDependency(dependencies, "org.junit.jupiter", "junit-jupiter", "5.9.2");
// Add build section with plugins
Element build = editor.insertMavenElement(root, BUILD);
Element plugins = editor.insertMavenElement(build, PLUGINS);
editor.addPlugin(plugins, "org.apache.maven.plugins", "maven-compiler-plugin", "3.11.0");
// Generate the XML
String result = editor.toXml();
```
--------------------------------
### Adding Dependencies (Core Library)
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Example of adding dependencies using the core DomTrip library.
```java
{cdi:snippets.snippet('maven-pom-adding-dependencies')}}
```
--------------------------------
### QuickStart Java XML Manipulation
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/syntax-test.html
Demonstrates parsing XML and adding a new element while preserving formatting using the Editor class.
```java
import eu.maveniverse.domtrip.Editor;
import eu.maveniverse.domtrip.Element;
public class QuickStart {
public static void main(String[] args) throws Exception {
// Parse XML while preserving all formatting
String originalXml = """
localhost
5432
""";
Editor editor = new Editor(originalXml);
Element database = editor.findElement("database");
editor.addElement(database, "username", "admin");
String result = editor.toXml();
System.out.println(result);
}
}
```
--------------------------------
### Integration Example: Building a Maven POM
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/element-positioning.md
Demonstrates how to use DomTrip's element manipulation methods, including insertion, to construct a Maven Project Object Model (POM) file.
```APIDOC
## Integration Example: Building a Maven POM
### Description
This example showcases building a Maven POM file programmatically using DomTrip's element creation and positioning APIs.
### Code Example
```java
Editor editor = new Editor();
editor.createDocument("project");
Element project = editor.root();
// Add basic coordinates
editor.addElement(project, "modelVersion", "4.0.0");
editor.addElement(project, "groupId", "com.example");
editor.addElement(project, "artifactId", "my-app");
editor.addElement(project, "version", "1.0.0");
// Insert packaging after version
Element version = project.child("version").orElseThrow();
editor.insertElementAfter(version, "packaging", "jar");
// Add dependencies section
Element dependencies = editor.addElement(project, "dependencies");
Element junit = editor.addElement(dependencies, "dependency");
editor.addElement(junit, "groupId", "junit");
editor.addElement(junit, "artifactId", "junit");
editor.addElement(junit, "scope", "test");
// Insert mockito before junit
Element mockito = editor.insertElementBefore(junit, "dependency");
editor.addElement(mockito, "groupId", "org.mockito");
editor.addElement(mockito, "artifactId", "mockito-core");
editor.addElement(mockito, "scope", "test");
```
```
--------------------------------
### Method Chaining Best Practice
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Example illustrating judicious use of method chaining for readability.
```java
Editor.of("root")
.element("child1")
.element("child2", "text");
```
--------------------------------
### Comment and Processing Instruction Handling Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Configure whether comments and processing instructions should be preserved during XML processing. This example preserves both.
```java
DomTripConfig config = DomTripConfig.defaults()
.withCommentPreservation(true)
.withProcessingInstructionPreservation(true);
```
--------------------------------
### Builder Composition Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Demonstrates combining multiple builders to construct complex XML document structures.
```java
Editor.of("root", ns -> {
ns.add(new ElementBuilder("customElement") {
// ... build custom element ...
});
});
```
--------------------------------
### Output XML structure
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/maven/quick-start.md
Example of the resulting XML structure after POM modification.
```xml
4.0.0
com.example
my-project
1.0.0
My Example Project
A sample project
```
--------------------------------
### Namespace Declaration Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Demonstrates how to handle XML namespaces using the builder pattern.
```java
ns.element("elementName", "value", "xmlns:prefix", "namespaceURI");
ns.element("elementName", "value", "prefix:attrName", "attrValue");
```
--------------------------------
### Fluent Element Builder Example
Source: https://github.com/maveniverse/domtrip/blob/main/README.md
Demonstrates creating a new XML element with attributes using DomTrip's fluent builder API.
```java
Element.builder("dependency").withAttribute("scope", "test").build()
```
--------------------------------
### Quote Style Configuration Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Define the default quote style for newly added attributes. This example sets the default to single quotes.
```java
DomTripConfig config = DomTripConfig.defaults()
.withDefaultQuoteStyle(QuoteStyle.SINGLE);
```
--------------------------------
### Example Maven POM Structure
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/maven/overview.md
Demonstrates the automatic blank line management and element ordering applied by the PomEditor.
```xml
4.0.0
org.example
parent
1.0.0
com.example
my-project
1.0.0
jar
My Project
An example project
```
--------------------------------
### Build a Maven POM
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/element-positioning.md
Example of constructing a Maven POM file using DomTrip's editor, including adding basic coordinates, inserting elements, and managing dependencies.
```java
Editor editor = new Editor();
editor.createDocument("project");
Element project = editor.root();
// Add basic coordinates
editor.addElement(project, "modelVersion", "4.0.0");
editor.addElement(project, "groupId", "com.example");
editor.addElement(project, "artifactId", "my-app");
editor.addElement(project, "version", "1.0.0");
// Insert packaging after version
Element version = project.child("version").orElseThrow();
editor.insertElementAfter(version, "packaging", "jar");
// Add dependencies section
Element dependencies = editor.addElement(project, "dependencies");
Element junit = editor.addElement(dependencies, "dependency");
editor.addElement(junit, "groupId", "junit");
editor.addElement(junit, "artifactId", "junit");
editor.addElement(junit, "scope", "test");
// Insert mockito before junit
Element mockito = editor.insertElementBefore(junit, "dependency");
editor.addElement(mockito, "groupId", "org.mockito");
editor.addElement(mockito, "artifactId", "mockito-core");
editor.addElement(mockito, "scope", "test");
```
--------------------------------
### Verify DomTrip Maven Extension Installation
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/maven/installation.md
A simple Java test to confirm the DomTrip Maven extension is installed and accessible. It checks for the availability of constants from the extension.
```java
import eu.maveniverse.domtrip.maven.PomEditor;
import eu.maveniverse.domtrip.maven.MavenPomElements;
public class InstallationTest {
public static void main(String[] args) {
// Create a new POM editor
PomEditor editor = new PomEditor();
// Verify constants are available
System.out.println("Maven namespace: " +
MavenPomElements.Namespaces.MAVEN_4_0_0_NAMESPACE);
System.out.println("DomTrip Maven extension installed successfully!");
}
}
```
--------------------------------
### Custom Builder Extensions
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Example of creating domain-specific builders for common XML patterns.
```java
public class MyCustomBuilder extends ElementBuilder {
public MyCustomBuilder(String name) {
super(name);
}
public MyCustomBuilder withCustomAttribute(String value) {
attr("customAttr", value);
return self();
}
}
```
--------------------------------
### Resource Cleanup Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/error-handling.md
Illustrates proper resource cleanup using try-with-resources or finally blocks. Essential for preventing resource leaks.
```java
try (InputStream stream = getInputStream()) {
// Process stream
} catch (IOException e) {
// Handle IO errors
}
```
--------------------------------
### Implement Phase 1 Gradual Migration
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/migration.md
Use this snippet to start using DomTrip for new XML processing code.
```java
{cdi:snippets.snippet('gradual-migration-phase1')}
```
--------------------------------
### Create Complete Maven POM with DomTrip
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/maven/examples.md
This example demonstrates how to create a full Maven POM file using the PomEditor API. It covers setting project coordinates, information, organization, licenses, properties, dependencies, and build configurations like plugins. Ensure the PomEditor class and related constants are available in your project.
```java
public class CompleteExample {
public static void main(String[] args) {
// Create enterprise Java project POM
PomEditor editor = new PomEditor();
editor.createMavenDocument("project");
Element root = editor.root();
// Project coordinates
editor.insertMavenElement(root, MODEL_VERSION, "4.0.0");
editor.insertMavenElement(root, GROUP_ID, "com.enterprise");
editor.insertMavenElement(root, ARTIFACT_ID, "enterprise-app");
editor.insertMavenElement(root, VERSION, "2.0.0");
editor.insertMavenElement(root, PACKAGING, "jar");
// Project information
editor.insertMavenElement(root, NAME, "Enterprise Application");
editor.insertMavenElement(root, DESCRIPTION, "A comprehensive enterprise Java application");
editor.insertMavenElement(root, URL, "https://github.com/enterprise/app");
editor.insertMavenElement(root, INCEPTION_YEAR, "2024");
// Organization
Element organization = editor.insertMavenElement(root, ORGANIZATION);
editor.addElement(organization, NAME, "Enterprise Corp");
editor.addElement(organization, URL, "https://enterprise.com");
// Licenses
Element licenses = editor.insertMavenElement(root, LICENSES);
Element license = editor.addElement(licenses, "license");
editor.addElement(license, NAME, "Apache License 2.0");
editor.addElement(license, URL, "https://www.apache.org/licenses/LICENSE-2.0");
// Properties with version management
Element properties = editor.insertMavenElement(root, PROPERTIES);
editor.addProperty(properties, "maven.compiler.source", "17");
editor.addProperty(properties, "maven.compiler.target", "17");
editor.addProperty(properties, "project.build.sourceEncoding", "UTF-8");
editor.addProperty(properties, "spring.version", "6.0.9");
editor.addProperty(properties, "junit.version", "5.9.2");
editor.addProperty(properties, "slf4j.version", "2.0.7");
// Dependencies
Element dependencies = editor.insertMavenElement(root, DEPENDENCIES);
// Production dependencies
editor.addDependency(dependencies, "org.springframework", "spring-context", "$\{spring.version}");
editor.addDependency(dependencies, "org.slf4j", "slf4j-api", "$\{slf4j.version}");
editor.addDependency(dependencies, "ch.qos.logback", "logback-classic", "1.4.7");
// Test dependencies
Element junitDep = editor.addDependency(dependencies,
"org.junit.jupiter", "junit-jupiter", "$\{junit.version}");
editor.insertMavenElement(junitDep, SCOPE, "test");
Element mockitoDep = editor.addDependency(dependencies,
"org.mockito", "mockito-core", "4.6.1");
editor.insertMavenElement(mockitoDep, SCOPE, "test");
// Build configuration
Element build = editor.insertMavenElement(root, BUILD);
editor.insertMavenElement(build, FINAL_NAME, "enterprise-app");
Element plugins = editor.insertMavenElement(build, PLUGINS);
// Compiler plugin
Element compilerPlugin = editor.addPlugin(plugins,
"org.apache.maven.plugins", "maven-compiler-plugin", "3.11.0");
Element compilerConfig = editor.insertMavenElement(compilerPlugin, CONFIGURATION);
editor.addElement(compilerConfig, "source", "$\{maven.compiler.source}");
editor.addElement(compilerConfig, "target", "$\{maven.compiler.target}");
// Surefire plugin
Element surefirePlugin = editor.addPlugin(plugins,
"org.apache.maven.plugins", "maven-surefire-plugin", "3.0.0");
// JAR plugin with manifest
Element jarPlugin = editor.addPlugin(plugins,
"org.apache.maven.plugins", "maven-jar-plugin", "3.3.0");
Element jarConfig = editor.insertMavenElement(jarPlugin, CONFIGURATION);
Element archive = editor.addElement(jarConfig, "archive");
Element manifest = editor.addElement(archive, "manifest");
editor.addElement(manifest, "mainClass", "com.enterprise.Application");
editor.addElement(manifest, "addClasspath", "true");
// Output the complete POM
System.out.println(editor.toXml());
}
}
```
--------------------------------
### Fluent Interface Design Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Demonstrates the fluent interface pattern allowing method chaining for readable code.
```java
Editor.of("root", ns -> {
ns.element("child", "text");
})
```
--------------------------------
### Edit Maven POM files
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/getting-started/quick-start.md
A practical example demonstrating how to modify a standard Maven project file.
```java
{cdi:snippets.snippet('real-world-maven-example')}
```
--------------------------------
### Modern Java API Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/introduction.md
Showcases the modern Java API provided by DomTrip for creating and manipulating XML structures fluently.
```java
{cdi:snippets.snippet('modern-java-api')}
```
--------------------------------
### Intelligent Editing Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/introduction.md
Illustrates DomTrip's intelligent editing capabilities, allowing modifications while maintaining document integrity.
```java
{cdi:snippets.snippet('intelligent-editing')}
```
--------------------------------
### Example Output XML
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/introduction.md
The resulting XML document after applying modifications using DomTrip, showing preserved comments, declarations, and formatting.
```xml
com.example
1.0.1
junit
junit
4.13.2
```
--------------------------------
### Visualize Empty Element Styles
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Examples of how different empty element styles appear in XML output.
```xml
```
--------------------------------
### Logging Integration
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/error-handling.md
Example of integrating DomTrip error handling with a logging framework. Ensures errors are recorded for monitoring and analysis.
```java
try {
// Process XML
} catch (DomTripException e) {
logger.error("XML Processing Error", e);
}
```
--------------------------------
### Memory Usage Comparison
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/lossless-parsing.md
This example compares the memory usage of a traditional XML parser with DomTrip, highlighting the approximate 20-30% overhead incurred by DomTrip to store formatting metadata.
```java
// Traditional parser memory usage
Document traditionalDoc = traditionalParser.parse(xml);
// Memory: ~1x base size
// DomTrip memory usage
Document domtripDoc = domtripParser.parse(xml);
// Memory: ~1.3x base size (includes formatting metadata)
```
--------------------------------
### Updating Version (Core Library)
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Example of updating an element's version using the core DomTrip library.
```java
{cdi:snippets.snippet('maven-pom-updating-version')}}
```
--------------------------------
### Validation Mode Configuration
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/error-handling.md
Example of setting the validation mode. This controls how DomTrip handles validation errors.
```java
DomTripParser parser = new DomTripParser();
parser.setValidationMode(ValidationMode.STRICT);
```
--------------------------------
### Handle Version Conflicts with Exclusions
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/maven/installation.md
Example of how to exclude transitive dependencies and explicitly declare versions to manage potential conflicts.
```xml
eu.maveniverse
domtrip-maven
0.2.0
*
*
eu.maveniverse
domtrip-core
0.2.0
```
--------------------------------
### Dual Content Storage for Text Nodes
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/lossless-parsing.md
This example shows DomTrip's internal representation of text nodes, storing both decoded content for programmatic access and raw content for serialization to preserve entities.
```java
// Internal representation
Text textNode = new Text(
"decoded content: < & >", // For your code to use
"raw content: < & >" // For serialization
);
// You work with decoded content
String content = textNode.getTextContent(); // "decoded content: < & >"
// Serialization uses raw content to preserve entities
String xml = textNode.toXml(); // "raw content: < & >"
```
--------------------------------
### XML Round-Tripping Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/comparison.md
Demonstrates how DomTrip preserves XML structure, including DOCTYPE, attributes, CDATA, and comments, resulting in identical output.
```xml
& content]]>
& content]]>
```
--------------------------------
### Round-Trip Preservation Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/introduction.md
Demonstrates DomTrip's ability to preserve the original XML document structure and details during round-trip operations.
```java
{cdi:snippets.snippet('round-trip-preservation')}
```
--------------------------------
### Run DomTrip Configuration Demo
Source: https://github.com/maveniverse/domtrip/blob/main/README.md
Launch the interactive demo for DomTrip's configuration options. Ensure tests are compiled first.
```bash
mvn test-compile exec:java -Dexec.mainClass="eu.maveniverse.domtrip.demos.ConfigurationDemo" -Dexec.classpathScope=test
```
--------------------------------
### Indentation Options Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Set the indentation string to be used when pretty printing XML. This example uses a tab character for indentation.
```java
DomTripConfig config = DomTripConfig.defaults()
.withIndentString("\t");
```
--------------------------------
### Integration Example: Reordering Elements
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/element-positioning.md
Illustrates how to reorder elements within a document by removing an element from its current position and inserting it at a new location.
```APIDOC
## Integration Example: Reordering Elements
### Description
This example demonstrates how to reorder elements within an XML document using DomTrip's removeNode and insertion methods.
### Code Example
```java
// Move an element to a different position
Element elementToMove = parent.child("target").orElseThrow();
Element referenceElement = parent.child("reference").orElseThrow();
// Remove from current position
parent.removeNode(elementToMove);
// Insert at new position
editor.insertElementBefore(referenceElement, elementToMove.name(), elementToMove.textContent());
```
```
--------------------------------
### Run DomTrip Builder Patterns Demo
Source: https://github.com/maveniverse/domtrip/blob/main/README.md
Launch the interactive demo for DomTrip's builder patterns. Ensure tests are compiled first.
```bash
mvn test-compile exec:java -Dexec.mainClass="eu.maveniverse.domtrip.demos.BuilderPatternsDemo" -Dexec.classpathScope=test
```
--------------------------------
### Java Class Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/syntax-debug.html
A simple Java class with a method that prints 'Hello World' to the console. This snippet is intended to demonstrate auto-detection of Java code.
```java
public class Test {
public void method() {
System.out.println("Hello World");
}
}
```
--------------------------------
### Best Practices for Simple Element and Node Creation in Java
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/factory-methods.md
Demonstrates preferred factory methods for creating elements, comments, and CDATA sections.
```java
// ✅ Good - clean and direct
Element version = Element.text("version", "1.0.0");
Comment comment = Comment.of("Configuration");
Text cdata = Text.cdata("script content");
// ❌ Avoid - unnecessary complexity
Element version = new Element("version");
version.addNode(new Text("1.0.0"));
```
--------------------------------
### Basic POM Creation with Maven Extension
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Shows how to create a basic Maven POM file using the DomTrip Maven extension.
```java
{cdi:snippets.snippet('basic-pom-creation')}
```
--------------------------------
### Attribute Manipulation
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Shows examples of manipulating attributes within XML elements.
```java
{cdi:snippets.snippet('attribute-manipulation')}
```
--------------------------------
### Java XML Editor Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/syntax-debug.html
Use this Java code to parse XML, find elements, add new elements, and convert back to XML using the Editor class. Ensure the domtrip library is available.
```java
import eu.maveniverse.domtrip.Editor;
import eu.maveniverse.domtrip.Element;
public class QuickStart {
public static void main(String[] args) throws Exception {
String xml = """
localhost
""";
Editor editor = new Editor(xml);
Element database = editor.findElement("database");
editor.addElement(database, "username", "admin");
String result = editor.toXml();
System.out.println(result);
}
}
```
--------------------------------
### PHP Processing Instruction
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/processing-instructions.md
Example of a processing instruction used for PHP code.
```java
var pi = new ProcessingInstruction("php", "echo \"Hello World\";", " ");
```
--------------------------------
### Run DomTrip Namespace Demo
Source: https://github.com/maveniverse/domtrip/blob/main/README.md
Launch the interactive demo for DomTrip's namespace handling. Ensure tests are compiled first.
```bash
mvn test-compile exec:java -Dexec.mainClass="eu.maveniverse.domtrip.demos.NamespaceDemo" -Dexec.classpathScope=test
```
--------------------------------
### Build the static website
Source: https://github.com/maveniverse/domtrip/blob/main/website/README.md
Executes a clean build and package of the website using the ROQ generator in batch mode.
```shell
QUARKUS_ROQ_GENERATOR_BATCH=true ./mvnw -f website clean package quarkus:run -DskipTests
```
--------------------------------
### Attribute Modification Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Illustrates how to modify attributes of an element using the builder.
```java
ns.element("elementName", "value", "attrName", "attrValue").attr("attrName", "newAttrValue");
```
--------------------------------
### Configure DomTrip
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/getting-started/basic-concepts.md
Sets up library behavior using the configuration system.
```java
{cdi:snippets.snippet('configuration-system')}
```
--------------------------------
### Basic Extensions Creation
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Demonstrates the basic creation of a Maven extensions.xml file.
```java
{cdi:snippets.snippet('basic-extensions-creation')}
```
--------------------------------
### Handle Invalid Encoding Exceptions
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/stream-support.md
Example of catching errors when an unsupported encoding is provided.
```java
try {
serializer.serialize(doc, outputStream, "INVALID-ENCODING");
} catch (DomTripException e) {
System.err.println("Unsupported encoding: " + e.getMessage());
}
```
--------------------------------
### Safe Element Handling
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Provides an example of safe element handling to prevent errors.
```java
{cdi:snippets.snippet('safe-element-handling')}
```
--------------------------------
### Define XML Namespaces
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/namespace-support.md
Example of an XML document structure utilizing multiple namespaces.
```xml
com.example
my-app
```
--------------------------------
### Adding Servers to Settings
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Demonstrates adding server configurations to a Maven settings.xml file.
```java
{cdi:snippets.snippet('adding-servers')}
```
--------------------------------
### Apply Configuration Best Practices
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Select appropriate presets based on the target use case, such as minimal for APIs or defaults for config files, and document specific settings.
```java
// ✅ Good - start with appropriate preset
DomTripConfig config = DomTripConfig.defaults() // For config files
.withIndentString(" "); // Customize as needed
// ✅ Good - use minimal for APIs
DomTripConfig apiConfig = DomTripConfig.minimal(); // Compact output
```
```java
// ✅ Good - document why you chose specific settings
DomTripConfig config = DomTripConfig.defaults()
.withIndentString(" ") // Match project style
.withDefaultQuoteStyle(QuoteStyle.DOUBLE) // Consistent with JSON
.withCommentPreservation(true); // Keep documentation
```
```java
// ✅ Good - different configs for different needs
DomTripConfig config = isProduction()
? DomTripConfig.defaults() // Preserve everything
: DomTripConfig.prettyPrint(); // Readable for debugging
```
--------------------------------
### Builder State Validation Example
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Shows how to validate the internal state of a builder before finalizing operations.
```java
if (builder.isValid()) {
// Proceed with building
} else {
// Handle invalid state
}
```
--------------------------------
### Run DomTrip Navigation Demo
Source: https://github.com/maveniverse/domtrip/blob/main/README.md
Launch the interactive demo for DomTrip's navigation features. Ensure tests are compiled first.
```bash
mvn test-compile exec:java -Dexec.mainClass="eu.maveniverse.domtrip.demos.NavigationDemo" -Dexec.classpathScope=test
```
--------------------------------
### Advanced Element Operations
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Provides examples of more complex element manipulations within the builder pattern.
```java
ns.element("elementName", ns2 -> {
ns2.element("nestedElement");
});
```
--------------------------------
### Run DomTrip Editor Demo
Source: https://github.com/maveniverse/domtrip/blob/main/README.md
Launch the interactive demo for DomTrip's core editing features. Ensure tests are compiled first.
```bash
mvn test-compile exec:java -Dexec.mainClass="eu.maveniverse.domtrip.demos.EditorDemo" -Dexec.classpathScope=test
```
--------------------------------
### Build DomTrip Website Documentation
Source: https://github.com/maveniverse/domtrip/blob/main/README.md
Build the production version of the DomTrip website documentation. Requires Node.js and npm.
```bash
cd website
npm install
npm run build
```
--------------------------------
### Processing Instruction with Special Characters
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/processing-instructions.md
Example of creating a processing instruction that includes special characters in its data.
```java
var pi = new ProcessingInstruction("app", "data with <>&\"");
```
--------------------------------
### Apply Namespace Best Practices
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/namespace-support.md
Recommended patterns for reliable namespace usage.
```java
{cdi:snippets.snippet('namespace-best-practices')}
```
--------------------------------
### List Available Configuration Methods
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Overview of the available methods for controlling formatting, content preservation, and attribute styles.
```java
DomTripConfig config = DomTripConfig.defaults()
// Formatting control
.withPrettyPrint(boolean) // Enable pretty printing
.withIndentString(String) // Set indentation string
.withLineEnding(String) // Set line ending style
// Content preservation
.withCommentPreservation(boolean) // Preserve comments
.withProcessingInstructionPreservation(boolean) // Preserve PIs
.withXmlDeclaration(boolean) // Include XML declaration
// Attribute formatting
.withDefaultQuoteStyle(QuoteStyle) // Default quote style for new attributes
// Empty element formatting
.withEmptyElementStyle(EmptyElementStyle) // Style for empty elements
.withAutoDetectedEmptyElementStyle(Document); // Auto-detect style from document
```
--------------------------------
### Sample XML Configuration
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/syntax-test.html
A sample XML structure representing database configuration.
```xml
localhost
5432
admin
secret
```
--------------------------------
### Basic Settings Creation
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Shows the basic creation of a Maven settings.xml file using the SettingsEditor.
```java
{cdi:snippets.snippet('basic-settings-creation')}
```
--------------------------------
### XML Declaration Handling
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Control the inclusion of the XML declaration in the output. Examples show how to include or omit the declaration.
```java
// Include XML declaration (default)
DomTripConfig withDeclaration = DomTripConfig.defaults()
.withXmlDeclaration(true);
// Omit XML declaration for minimal output
DomTripConfig withoutDeclaration = DomTripConfig.defaults()
.withXmlDeclaration(false);
```
--------------------------------
### Input Validation Snippet
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/error-handling.md
Example of validating input before processing. This prevents errors by ensuring data integrity upfront.
```java
if (!isValidInput(data)) {
throw new IllegalArgumentException("Invalid input data");
}
```
--------------------------------
### Using Builder Patterns
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Demonstrates the use of builder patterns for constructing XML elements.
```java
{cdi:snippets.snippet('using-builder-patterns')}
```
--------------------------------
### Handling Namespace Conflicts
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/error-handling.md
Example of catching exceptions for namespace conflicts. This is useful for resolving issues with XML namespaces.
```java
try {
// Process XML
} catch (NamespaceException e) {
// Handle namespace conflicts
}
```
--------------------------------
### Processing Instructions with Builder
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/builder-patterns.md
Illustrates adding XML processing instructions to the document.
```java
ns.processingInstruction("target", "data");
```
--------------------------------
### Insert Element at Specific Index
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/element-positioning.md
Example of inserting a new element at a specific index within a parent, with automatic indentation.
```java
Element newElement = editor.insertElementAt(parent, 1, "child");
```
--------------------------------
### Best Practices
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/editor.md
Provides guidance on best practices for using the DomTrip editor, including null checks, batch operations, and exception handling.
```APIDOC
## Best Practices
### 1. Check for Null Returns
Ensure safe navigation by checking for null values before accessing properties or methods of returned objects.
### 2. Use Batch Operations
For efficiency, utilize batch operations when performing multiple edits or additions.
### 3. Handle Exceptions Appropriately
Implement specific exception handling for `ParseException`, `InvalidXmlException`, and `DomTripException` to manage errors gracefully.
```
--------------------------------
### Adding Mirrors to Settings
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Illustrates adding mirror configurations to a Maven settings.xml file.
```java
{cdi:snippets.snippet('adding-mirrors')}
```
--------------------------------
### Handling Malformed XML
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/error-handling.md
Example of catching exceptions related to malformed XML. Ensure robust parsing by handling these errors.
```java
try {
// Process XML
} catch (ParsingException e) {
// Handle malformed XML
}
```
--------------------------------
### Basic Toolchains Creation
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Shows the basic creation of a Maven toolchains.xml file.
```java
{cdi:snippets.snippet('basic-toolchains-creation')}
```
--------------------------------
### Create XML Documents
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/document.md
Use factory methods to initialize new document instances.
```java
{cdi:snippets.snippet('document-creation')}
```
--------------------------------
### Adding JDK Toolchains
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Demonstrates adding JDK toolchain configurations to a Maven toolchains.xml file.
```java
{cdi:snippets.snippet('adding-jdk-toolchains')}
```
--------------------------------
### Adding Extensions
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Illustrates how to add Maven extensions to an extensions.xml file.
```java
{cdi:snippets.snippet('adding-extensions')}
```
--------------------------------
### Simple Document Creation in Java
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/factory-methods.md
Create a basic XML document with a root element.
```java
Document document = Document.of(Element.of("root"));
```
--------------------------------
### Handling Encoding Issues
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/error-handling.md
Example of catching exceptions for encoding problems. This helps manage issues with character encoding during XML processing.
```java
try {
// Process XML
} catch (EncodingException e) {
// Handle encoding issues
}
```
--------------------------------
### Create a complete Maven POM with PomEditor
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/maven/quick-start.md
Demonstrates the full lifecycle of creating a Maven project document, adding metadata, defining properties, managing dependencies, and configuring build plugins.
```java
public class CompletePomExample {
public static void main(String[] args) {
PomEditor editor = new PomEditor();
editor.createMavenDocument("project");
Element root = editor.root();
// Basic project info
editor.insertMavenElement(root, MODEL_VERSION, "4.0.0");
editor.insertMavenElement(root, GROUP_ID, "com.example");
editor.insertMavenElement(root, ARTIFACT_ID, "complete-example");
editor.insertMavenElement(root, VERSION, "1.0.0");
editor.insertMavenElement(root, PACKAGING, "jar");
// Metadata
editor.insertMavenElement(root, NAME, "Complete Example");
editor.insertMavenElement(root, DESCRIPTION, "A complete Maven project example");
editor.insertMavenElement(root, URL, "https://github.com/example/complete-example");
// Properties
Element properties = editor.insertMavenElement(root, PROPERTIES);
editor.addProperty(properties, "maven.compiler.source", "17");
editor.addProperty(properties, "maven.compiler.target", "17");
editor.addProperty(properties, "project.build.sourceEncoding", "UTF-8");
editor.addProperty(properties, "junit.version", "5.9.2");
// Dependencies
Element dependencies = editor.insertMavenElement(root, DEPENDENCIES);
// Production dependencies
editor.addDependency(dependencies, "org.slf4j", "slf4j-api", "2.0.7");
editor.addDependency(dependencies, "ch.qos.logback", "logback-classic", "1.4.7");
// Test dependencies
Element junitDep = editor.addDependency(dependencies,
"org.junit.jupiter", "junit-jupiter", "${junit.version}");
editor.insertMavenElement(junitDep, SCOPE, "test");
// Build configuration
Element build = editor.insertMavenElement(root, BUILD);
Element plugins = editor.insertMavenElement(build, PLUGINS);
// Compiler plugin
Element compilerPlugin = editor.addPlugin(plugins,
"org.apache.maven.plugins", "maven-compiler-plugin", "3.11.0");
Element compilerConfig = editor.insertMavenElement(compilerPlugin, CONFIGURATION);
editor.addElement(compilerConfig, "source", "${maven.compiler.source}");
editor.addElement(compilerConfig, "target", "${maven.compiler.target}");
// Surefire plugin
editor.addPlugin(plugins, "org.apache.maven.plugins", "maven-surefire-plugin", "3.0.0");
System.out.println(editor.toXml());
}
}
```
--------------------------------
### Performance Optimizations with Factory Methods and Fluent APIs in Java
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/factory-methods.md
Explains the performance benefits of DomTrip's factory methods and fluent APIs, such as memory efficiency and direct object creation.
```java
// Factory methods and fluent APIs are optimized for both convenience and performance:
// - Memory efficient: No intermediate builder objects created
// - Validation: Early validation prevents invalid XML structures
// - Direct creation: Objects created immediately, not deferred
// - Method chaining: Returns `this` for zero-cost fluent chaining
```
--------------------------------
### Basic Attribute Operations
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/element.md
Perform basic operations like getting, setting, and removing attributes from an element. Attribute names are case-sensitive.
```java
element.attribute("name", "value");
String value = element.attribute("name");
boolean hasAttribute = element.hasAttribute("name");
element.removeAttribute("name");
```
--------------------------------
### Adding Plugins with Maven Extension
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Illustrates adding plugins to a Maven POM file using the DomTrip Maven extension.
```java
{cdi:snippets.snippet('adding-plugins')}
```
--------------------------------
### Preset: Minimal Configuration
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Use the minimal configuration for compact XML output, optimizing for size by removing whitespace, comments, and declarations.
```java
DomTripConfig minimal = DomTripConfig.minimal();
```
--------------------------------
### Working with Namespaces
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Illustrates how to handle XML namespaces during editing.
```java
{cdi:snippets.snippet('working-with-namespaces')}
```
--------------------------------
### Load XML from various sources
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/getting-started/quick-start.md
Methods for initializing a DomTrip editor from strings, files, input streams, or configuration objects.
```java
{cdi:snippets.snippet('loading-xml-string')}
```
```java
{cdi:snippets.snippet('loading-xml-from-file')}
```
```java
{cdi:snippets.snippet('loading-xml-from-inputstream')}
```
```java
{cdi:snippets.snippet('loading-xml-config')}
```
--------------------------------
### Configuration Access
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/editor.md
Demonstrates how to access the configuration used by the DomTrip editor.
```APIDOC
## config()
### Description
Gets the configuration used by this editor.
### Method
Not specified (likely a getter method)
### Endpoint
Not applicable (method call)
### Parameters
None
### Request Example
```java
// Assuming 'editor' is an instance of the Editor class
Configuration config = editor.config();
```
### Response
Returns the editor's configuration object.
```
--------------------------------
### Line Ending Configuration
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/configuration.md
Specify the line ending characters to be used in the output XML. Examples show Unix, Windows, and Mac line endings.
```java
// Use Unix line endings
DomTripConfig unix = DomTripConfig.defaults()
.withLineEnding("\n");
// Use Windows line endings
DomTripConfig windows = DomTripConfig.defaults()
.withLineEnding("\r\n");
// Use Mac line endings
DomTripConfig mac = DomTripConfig.defaults()
.withLineEnding("\r");
```
--------------------------------
### Adding Profiles to Settings
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Shows how to add profile configurations to a Maven settings.xml file.
```java
{cdi:snippets.snippet('adding-profiles')}
```
--------------------------------
### Basic Text Content Operations
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/element.md
Handle basic text content of an element, including getting and setting text. Note that this may not preserve whitespace.
```java
element.text("Some text");
String text = element.text();
```
--------------------------------
### Attribute Management
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/editor.md
Set, get, remove, and batch set attributes on XML elements. The API intelligently preserves formatting and infers styles for new attributes.
```java
Element targetElement = ...; // Target Element object
editor.setAttribute(targetElement, "attributeName", "attributeValue");
```
```java
Element targetElement = ...; // Target Element object
String value = editor.getAttribute(targetElement, "attributeName");
```
```java
Element targetElement = ...; // Target Element object
editor.removeAttribute(targetElement, "attributeName");
```
```java
Element targetElement = ...; // Target Element object
Map attrs = new HashMap<>();
attrs.put("attr1", "val1");
attrs.put("attr2", "val2");
editor.setAttributes(targetElement, attrs);
```
```java
// For advanced control, work with Attribute objects directly:
Element targetElement = ...;
Attribute attr = new Attribute("name", "value");
editor.setAttribute(targetElement, attr);
```
--------------------------------
### Adding Various Toolchains
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/examples/index.md
Illustrates adding various types of toolchain configurations to a Maven toolchains.xml file.
```java
{cdi:snippets.snippet('adding-various-toolchains')}
```
--------------------------------
### Element Tag Whitespace Management
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/api/element.md
Manage whitespace specifically within the element's start and end tags. This influences the spacing between the tag name and attributes, or before the closing tag.
```java
element.tagLeadingWhitespace(" ");
String tagLeading = element.tagLeadingWhitespace();
element.tagTrailingWhitespace(" ");
String tagTrailing = element.tagTrailingWhitespace();
```
--------------------------------
### Run performance tests
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/features/performance.md
Executes standard performance benchmarks for DomTrip.
```java
{cdi:snippets.snippet('performance-testing')}
```
--------------------------------
### Basic Element Creation in Java
Source: https://github.com/maveniverse/domtrip/blob/main/website/content/docs/advanced/factory-methods.md
Use this for simple element creation without attributes or content.
```java
Element element = Element.of("myElement");
```
--------------------------------
### Manage Element Attributes with Formatting Preservation
Source: https://context7.com/maveniverse/domtrip/llms.txt
Use these methods to get, set, check, and remove attributes, preserving quote styles and whitespace. Advanced usage involves Attribute objects for fine-grained control.
```java
String scope = element.attribute("scope");
```
```java
element.attribute("version", "2.0");
```
```java
element.attribute("path", "/home/user", QuoteStyle.SINGLE);
```
```java
boolean hasScope = element.hasAttribute("scope");
```
```java
element.removeAttribute("deprecated");
```
```java
Map attrs = element.attributes();
```
```java
Attribute attr = element.attributeObject("scope");
QuoteStyle quoteStyle = attr.quoteStyle();
String precedingWhitespace = attr.precedingWhitespace();
String rawValue = attr.rawValue();
```
```java
element.attributeWhitespace("attr2", "\n ");
```
```java
element.attributeQuote("path", QuoteStyle.SINGLE);
```
--------------------------------
### Edit Maven POM File with Formatting Preservation
Source: https://context7.com/maveniverse/domtrip/llms.txt
A comprehensive example demonstrating how to load, modify, and save a Maven POM file using DomTrip's Editor API. This includes updating versions, adding dependencies, removing elements, and updating properties while preserving the original formatting.
```java
// Load existing POM
Document pom = Document.of(Paths.get("pom.xml"));
Editor editor = new Editor(pom);
Element project = editor.root();
```
```java
// Update version
project.descendant("version")
.ifPresent(v -> editor.setTextContent(v, "2.0.0-SNAPSHOT"));
```
```java
// Add a new dependency
Element dependencies = project.descendant("dependencies")
.orElseGet(() -> editor.addElement(project, "dependencies"));
Element newDep = editor.addElement(dependencies, "dependency");
editor.addElement(newDep, "groupId", "org.junit.jupiter");
editor.addElement(newDep, "artifactId", "junit-jupiter");
editor.addElement(newDep, "version", "5.10.0");
editor.addElement(newDep, "scope", "test");
```
```java
// Add a comment before the new dependency
editor.addBlankLineBefore(newDep);
```
```java
// Remove deprecated dependencies
project.descendants("dependency")
.filter(dep -> "old-library".equals(dep.childText("artifactId")))
.forEach(editor::removeElement);
```
```java
// Update properties
Element properties = project.descendant("properties")
.orElseGet(() -> {
Element props = editor.addElement(project, "properties");
editor.insertElementBefore(
project.childElement("dependencies").orElse(null),
"properties"
);
return props;
});
properties.childElement("java.version")
.ifPresentOrElse(
v -> editor.setTextContent(v, "17"),
() -> editor.addElement(properties, "java.version", "17")
);
```
```java
// Save with preserved formatting
String result = editor.toXml();
Files.writeString(Paths.get("pom.xml"), result);
```