• 1.4

JAXB Converter

The object has to be annotated with JAXB annotations in order to be convertable. Let's consider an example JAXB-annotated class:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.NONE)
public class Employee {
  @XmlElement(name = "name")
  public String getName() {
    return "John Doe";
  }
}

Now you want to test how it works with real data after convertion to XML (in a unit test):

import com.jcabi.matchers.JaxbConverter;
import com.jcabi.matchers.XhtmlMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
public class EmployeeTest {
  @Test
  public void testObjectToXmlConversion() throws Exception {
    final Object object = new Employee();
    MatcherAssert.assertThat(
      JaxbConverter.the(object),
      XhtmlMatchers.hasXPath("/employee/name[.='John Doe']")
    );
  }
}

These dependencies you will need in your pom.xml:

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-library</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-core</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>com.jcabi</groupId>
  <artifactId>jcabi-xml</artifactId>
  <version>0.7.8</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.2.11</version>
  <scope>provided</scope>
</dependency>