原创文章,转载请注明出处。http://www.blogjava.net/kangdy/archive/2011/11/23/364635.html
code1: colors类 根节点
code1
package com.kangdy.test;
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 = "Colors")
@XmlAccessorType(XmlAccessType.FIELD)
public class Colors {
@XmlElement(name = "red",nillable=true)
private Red red;
@XmlElement(name = "blue",nillable=true)
private Blue blue;
public Red getRed() {
return red;
}
public Blue getBlue() {
return blue;
}
public void setRed(Red red) {
this.red = red;
}
public void setBlue(Blue blue) {
this.blue = blue;
}
}
code2: Red类 子节点
code2package com.kangdy.test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "red")
@XmlAccessorType(XmlAccessType.FIELD)
public class Red {
private String value;
@XmlAttribute(name = "att1")
private String att;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getAtt() {
return att;
}
public void setAtt(String att) {
this.att = att;
}
}
code3: 类 Blue 子节点
code3
package com.kangdy.test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "blue")
@XmlAccessorType(XmlAccessType.FIELD)
public class Blue {
private String value;
@XmlAttribute(name = "att2")
private String att2;
@XmlAttribute(name = "att1")
private String att;
public String getAtt() {
return att;
}
public void setAtt(String att) {
this.att = att;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getAtt2() {
return att2;
}
public void setAtt2(String att2) {
this.att2 = att2;
}
}
code4: main类
code4
package com.kangdy.test;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Jaxbtest {
public static void main(String[] args) throws Exception {
StringWriter writer = new StringWriter();
JAXBContext jc = JAXBContext.newInstance(Colors.class);
Marshaller ma = jc.createMarshaller();
ma.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Colors colors = new Colors();
Red red = new Red();
red.setAtt("att-red");
red.setValue("red");
Blue blue = new Blue();
blue.setValue("blue");
blue.setAtt("att-blue");
blue.setAtt2("blue-att2");
colors.setRed(red);
colors.setBlue(blue);
ma.marshal(colors, writer);
System.out.println(writer.toString());
}
}
运行结果:
结果
red
blue
posted on 2011-11-23 14:33 AK47 阅读(9362) 评论(4) 编辑 收藏 所属分类: java相关