Skip to content

evolvedbinary/j8xu

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java 8 XML Utilities

CircleCI Coverage Status Java 8 License Maven Central

Some extra utility classes for making working with XML in Java just that little bit easier.

The main thing here at the moment is a DSL like Builder Pattern for programmatically constructing.

Maven Dependency

You can add the library to your project as a dependency with the following Maven coordinates:

<dependency>
    <groupId>com.evolvedbinary.j8xu</groupId>
    <artifactId>j8xu</artifactId>
    <version>1.0.0</version>
</dependency>

XML Builder

The project is split into an API and implementations. The main API class of interest is XmlBuilder and where you should start from. At the moment there is a single implementation StringXmlBuilder, however implementing the API is trivial, and you are free to create your own implementations.

The XmlBuilder provides methods for constructing all XML Node types:

  • document
  • element
  • attributes
  • text
  • cdata
  • comment

There are several overloaded element methods to allow you to specify the namespace and/or prefixes for an element, and any attributes.

String XML Builder Example

import com.evolvedbinary.j8xu.builder.api.XmlBuilder;
import com.evolvedbinary.j8xu.builder.api.XmlDocumentBuilder;
import static com.evolvedbinary.j8xu.builder.api.XmlBuilder.attribute;

import com.evolvedbinary.j8xu.builder.impl.string.StringXmlBuilder;

public class Example {

  public static void main(String args[]) {

    XmlBuilder<String> x = new StringXmlBuilder();  // or instantiate your own implementation here

    XmlDocumentBuilder<String> document = x.document(
        x.comment("start of the doc"),
        x.element("http://example.com/people", "people",
            x.element("person",
                x.attributes(
                    attribute("id", 1)
                ),
                x.element("firstName", x.text("john")),
                x.element("lastName", x.text("doe")),
                x.element("phone", x.text("555-555-55")),
                x.element("status")
            )
        ),
        x.comment("end of the doc")
    );

    String asString = document.build();
    System.out.println(asString);
  }
}