简单的Java到XML示例 [英] Simple Java to XML example
本文介绍了简单的Java到XML示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚才读过关于使用注释从Java生成xml的内容,但我现在找不到一个简单的例子。
I've read a time ago about generate xml from Java using annotations, but I'm not finding a simple example now.
如果我想制作一个xml文件如:
If I want to make a xml file like:
<x:element uid="asdf">value</x:element>
:
public class Element {
private String uid = "asdf";
private String value = "value";
}
我应该使用哪些注释来执行此操作? (我有一个xml架构,如果这有助于生成)
Which annotations should I use to perform that? (I have a xml-schema, if this helps the generation)
- 更新
javax .xml.bind.annotation 包有注释,但我仍然没有找到我正在寻找的东西:用法的例子.. :)
The javax.xml.bind.annotation package have the annotations, "but I still haven't found what I'm looking for": an exemple of usage.. :)
推荐答案
找到它:
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>
这篇关于简单的Java到XML示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文