Simple Java-XML Example

I have long read about creating xml from Java using annotations, but right now I can not find a simple example.

If I want to create an xml file, for example:

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

from my java class:

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

What annotations should I use to accomplish this? (I have an xml scheme if this helps the generation)

- update

There are annotations in the javax.xml.bind.annotation package "but I still haven't found what I was looking for": an example of use .. :)

+3
source share
3 answers

Found:

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

+1
source

, . XStream (http://x-stream.imtqy.com/) - , XML, .

+1

In the interest of someone else hitting this stream, I suppose you did the following:

@XmlRootElement
public class Element { 

  @XmlAttribute
  private String uid = "asdf"; 

  @XmlValue
  private String value = "value"; 
} 

Additional Information

+1
source

Source: https://habr.com/ru/post/1746230/


All Articles