Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Java to XML example

Tags:

java

xml

I've read a time ago about generate xml from Java using annotations, but I'm not finding a simple example now.

If I want to make a xml file like:

<x:element uid="asdf">value</x:element>

from my java class:

public class Element {
  private String uid = "asdf";
  private String value = "value";
}

Which annotations should I use to perform that? (I have a xml-schema, if this helps the generation)

--update

The javax.xml.bind.annotation package have the annotations, "but I still haven't found what I'm looking for": an exemple of usage.. :)

like image 969
The Student Avatar asked Aug 28 '26 06:08

The Student


2 Answers

Found it:

import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;

public class JavaToXMLDemo {
  public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Employee.class);

    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Employee object = new Employee();
    object.setCode("CA");
    object.setName("Cath");
    object.setSalary(300);

    m.marshal(object, System.out);

  }
}

@XmlRootElement
class Employee {
  private String code;

  private String name;

  private int salary;

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int population) {
    this.salary = population;
  }
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <code>CA</code>
    <name>Cath</name>
    <salary>300</salary>
</employee>

From: http://www.java2s.com/Code/JavaAPI/javax.xml.bind.annotation/javaxxmlbindannotationXmlRootElement.htm

like image 155
The Student Avatar answered Aug 30 '26 19:08

The Student


For the benefit of anyone else hitting this thread, I imagine you did the following:

@XmlRootElement
public class Element { 

  @XmlAttribute
  private String uid = "asdf"; 

  @XmlValue
  private String value = "value"; 
} 

For More Information

  • http://bdoughan.blogspot.com/2011/06/jaxb-and-complex-types-with-simple.html
like image 40
bdoughan Avatar answered Aug 30 '26 21:08

bdoughan