Skip to content

Update documentation for v1.1.0 release #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 160 additions & 16 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,38 @@
# Examples

In the following examples, we showcase how DomUtils, a utility class in the commons-xml project, can be utilized to simplify XML processing tasks. DomUtils provides convenient methods and functionalities for tasks such as parsing XML, manipulating nodes, validating documents, and extracting information using XPath expressions. Through these code snippets, you will gain insights into how to effectively use DomUtils to insert elements, copy attributes and children, rename nodes, convert nodes to XML strings, and more.

## Example of using `DomUtils.parse(String)`
# Commons-XML Examples

This document provides comprehensive examples of using the commons-xml library for various XML processing tasks. The library's main utility class, `DomUtils`, offers a wide range of methods for parsing, manipulating, validating, and querying XML documents.

## Table of Contents

- [Parsing XML](#parsing-xml)
- [Parse XML from String](#parse-xml-from-string)
- [Parse XML from File](#parse-xml-from-file)
- [Parse XML from Resource](#parse-xml-from-resource)
- [DOM Manipulation](#dom-manipulation)
- [Insert Element with Ordering](#insert-element-with-ordering)
- [Insert Element Before Reference Node](#insert-element-before-reference-node)
- [Insert Element After Reference Node](#insert-element-after-reference-node)
- [Delete Multiple Nodes](#delete-multiple-nodes)
- [XPath Queries](#xpath-queries)
- [Select String Value with XPath](#select-string-value-with-xpath)
- [Select Child Nodes](#select-child-nodes)
- [XPath with Multiple Results](#xpath-with-multiple-results)
- [Node Operations](#node-operations)
- [Copy Attributes Between Elements](#copy-attributes-between-elements)
- [Copy Children Between Elements](#copy-children-between-elements)
- [Rename Node](#rename-node)
- [Validation](#validation)
- [Validate Document Against Schema](#validate-document-against-schema)
- [Schema Validation with Error Handling](#schema-validation-with-error-handling)
- [Serialization](#serialization)
- [Convert Node to XML String](#convert-node-to-xml-string)
- [Additional Examples](#additional-examples)
- [Working with Namespaces](#working-with-namespaces)
- [Create Document with Elements](#create-document-with-elements)

## Parsing XML

### Parse XML from String

```java
import com.dataliquid.commons.xml.DomUtils;
Expand All @@ -13,7 +43,9 @@ Document document = DomUtils.parse(xmlString);
// You can further process the parsed Document object here
```

## Example of using `DomUtils.insertElement(Node, Element, List<String>)`
## DOM Manipulation

### Insert Element with Ordering

```java
import org.w3c.dom.Element;
Expand All @@ -32,7 +64,7 @@ Element insertedElement = DomUtils.insertElement(parentNode, elementToInsert, or
// You can further process the insertedElement here
```

## Example of using `DomUtils.insertElementBefore(Node, Element)`
### Insert Element Before Reference Node

```java
import org.w3c.dom.Element;
Expand All @@ -47,7 +79,7 @@ Element insertedElement = DomUtils.insertElementBefore(referenceNode, elementToI
// The method inserts the Element before the reference Node and returns the inserted Element
```

## Example of using `DomUtils.insertElementAfter(Node, Element)`
### Insert Element After Reference Node

```java
import org.w3c.dom.Element;
Expand All @@ -62,7 +94,7 @@ Element insertedElement = DomUtils.insertElementAfter(referenceNode, elementToIn
// The method inserts the Element after the reference Node and returns the inserted Element
```

## Example of using `DomUtils.delete(List<Node>)`
### Delete Multiple Nodes

```java
import org.w3c.dom.Node;
Expand All @@ -75,7 +107,9 @@ DomUtils.delete(nodesToDelete);
// The nodes in the list are deleted from their parent nodes
```

## Example of using `DomUtils.selectString(Node, String)`
## XPath Queries

### Select String Value with XPath

```java
import org.w3c.dom.Node;
Expand All @@ -91,7 +125,7 @@ String selectedString = DomUtils.selectString(node, xpath);
// You can further process the selectedString here
```

## Example of using `DomUtils.selectChildNodes(Node)`
### Select Child Nodes

```java
import org.w3c.dom.Node;
Expand All @@ -106,7 +140,9 @@ List<Node> childNodes = DomUtils.selectChildNodes(parentNode);
// You can further process the childNodes list here
```

## Example of using `DomUtils.copyAttributes(Element, Element)`
## Node Operations

### Copy Attributes Between Elements

```java
import org.w3c.dom.Element;
Expand All @@ -120,7 +156,7 @@ DomUtils.copyAttributes(sourceElement, destinationElement);
// The method copies the attributes from the source element to the destination element
```

## Example of using `DomUtils.copyChildren(Element, Element)`
### Copy Children Between Elements

```java
import org.w3c.dom.Element;
Expand All @@ -134,7 +170,7 @@ DomUtils.copyChildren(sourceElement, destinationElement);
// The method copies the children nodes from the source element to the destination element
```

## Example of using `DomUtils.renameNode(Node, String)`
### Rename Node

```java
import org.w3c.dom.Node;
Expand All @@ -148,7 +184,9 @@ Node renamedNode = DomUtils.renameNode(node, newName);
// The method renames the node with the new name and returns the renamed node
```

## Example of using `DomUtils.validate(Document, Schema)`
## Validation

### Validate Document Against Schema

```java
import org.w3c.dom.Document;
Expand All @@ -171,7 +209,9 @@ if (isValid) {
}
```

## Example of using `DomUtils.asXml(Node, boolean)`
## Serialization

### Convert Node to XML String

```java
import org.w3c.dom.Node;
Expand All @@ -185,4 +225,108 @@ String xmlString = DomUtils.asXml(node, indent);
// The method converts the Node to its XML representation as a String

// You can further process the xmlString here
```

## Additional Examples

### Parse XML from File

```java
import com.dataliquid.commons.xml.DomUtils;
import java.io.File;

File xmlFile = new File("path/to/your/file.xml");
Document document = DomUtils.parse(xmlFile);
```

### Parse XML from Resource

```java
import com.dataliquid.commons.xml.DomUtils;

// Parse XML from classpath resource
Document document = DomUtils.parseResource("xml/config.xml");
```

### Working with Namespaces

```java
import com.dataliquid.commons.xml.DomUtils;
import com.dataliquid.commons.xml.ns.DefaultNamespaceContext;
import javax.xml.namespace.NamespaceContext;

// Create namespace context
DefaultNamespaceContext nsContext = new DefaultNamespaceContext();
nsContext.addNamespace("ns", "http://example.com/namespace");

// Use namespace in XPath queries
Node node = ...; // Your node
String value = DomUtils.selectString(node, "//ns:element/text()", nsContext);
```

### Create Document with Elements

```java
import com.dataliquid.commons.xml.DomUtils;
import org.w3c.dom.*;

// Create new document
Document doc = DomUtils.createDocument();

// Create root element with namespace
Element root = DomUtils.createElement(doc, "root", "http://example.com/ns");
doc.appendChild(root);

// Add child elements
Element child = DomUtils.createElement(doc, "child");
DomUtils.setTextContent(child, "Some content");
root.appendChild(child);

// Add attributes
DomUtils.setAttribute(child, "id", "123");
DomUtils.setAttribute(child, "type", "example");
```

### XPath with Multiple Results

```java
import com.dataliquid.commons.xml.DomUtils;
import org.w3c.dom.NodeList;

Document doc = ...; // Your document
NodeList nodes = DomUtils.selectNodes(doc, "//item[@active='true']");

for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
String value = DomUtils.getTextContent(node);
System.out.println("Item value: " + value);
}
```

### Schema Validation with Error Handling

```java
import com.dataliquid.commons.xml.DomUtils;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.XMLConstants;
import java.io.File;

try {
// Load schema
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File("schema.xsd"));

// Validate document
Document document = DomUtils.parse(new File("document.xml"));
boolean isValid = DomUtils.validate(document, schema);

if (isValid) {
System.out.println("Document is valid");
} else {
System.out.println("Document validation failed");
}
} catch (Exception e) {
System.err.println("Validation error: " + e.getMessage());
}
```
50 changes: 21 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,41 @@
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.dataliquid/commons-xml/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.dataliquid/commons-xml)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

Welcome to the `commons-xml` project! This repository contains a Java library that provides various utility classes and functions for working with XML documents. The library is designed to make common tasks related to XML processing and manipulation easier.
A lightweight and efficient Java library for XML processing and manipulation. This library provides comprehensive utilities for parsing, creating, validating, and transforming XML documents with a focus on simplicity and performance.

## Features

- **XML Parsing**: The library provides an easy way to parse XML documents and convert them into a structured data format.
- **XML Creation**: You can programmatically create XML documents while maintaining the desired structure and hierarchy.
- **XPath Support**: The library allows you to use XPath expressions to selectively access specific elements or attributes in an XML document.
- **Validation**: You can validate XML documents against an XML schema and ensure they adhere to the specified rules.
- **XML Parsing**: Easy-to-use utilities for parsing XML documents from files, resources, or strings
- **XML Creation**: Programmatic XML document creation with fluent API
- **XPath Support**: Advanced XPath expression support with namespace handling
- **Schema Validation**: Validate XML documents against XSD schemas
- **DOM Manipulation**: Comprehensive DOM utilities for working with XML elements and attributes
- **Namespace Support**: Built-in namespace context management for complex XML documents

## Requirements

- Java 8 or higher (supports Java 8, 11, 17, and 21)
- Maven 3.6 or higher

## Usage

To use the `commons-xml` library in your project, you can add it as a Maven dependency. Add the following section to your `pom.xml` file:
## Installation

### Maven
```xml
<dependencies>
<dependency>
<groupId>com.dataliquid</groupId>
<artifactId>commons-xml</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>
<dependency>
<groupId>com.dataliquid</groupId>
<artifactId>commons-xml</artifactId>
<version>1.1.0</version>
</dependency>
```

## Example

The given example utilizes the DomUtils class from the commons-xml library to create and manipulate an XML document. It performs the following steps:
### Gradle
```gradle
implementation 'com.dataliquid:commons-xml:1.1.0'
```

- Creates an empty XML document using DomUtils.createDocument().
- Creates a root element named "root" and adds it to the document.
- Creates a child element named "child" and sets its text content to "Hello, World!". The child element is appended to the root element.
- Converts the document to an XML string representation using DomUtils.asXml(document).
- Prints the generated XML string to the console.
## Quick Start

In summary, this example demonstrates how to create an XML document, add elements to it, and obtain the XML representation of the document using the DomUtils class.
Here's a simple example demonstrating XML document creation and manipulation:

```java
import com.dataliquid.commons.xml.DomUtils;
Expand Down Expand Up @@ -70,11 +66,7 @@ public class Example {
}
```

This example demonstrates the usage of the `DomUtils` class to create an XML document, add a root element and a child element to it. Then, it retrieves the xml as string and print it out.

Please note that you need to add the `commons-xml` library to your project in order to use the `DomUtils` class.

Follow this link, you will be taken to the [EXAMPLES.md](EXAMPLES.md) file where you can find more examples. These examples are intended to help you understand and utilize the functionality of the Commons-XML project.
For more detailed examples including XPath queries, namespace handling, and schema validation, see [EXAMPLES.md](EXAMPLES.md).

## Building from Source

Expand Down
Loading