Java HTML/XML - 如何使用jaxb在XML中執(zhí)行自動(dòng)增量ID
我們想知道如何使用jaxb在XML中執(zhí)行自動(dòng)增量ID。
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
public class Main {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Messages.class);
Messages messages = new Messages();
messages.getMessages().add(new Message());
messages.getMessages().add(new Message());
messages.getMessages().add(new Message());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setAdapter(new IDAdapter());
marshaller.marshal(messages, System.out);
}
@XmlAccessorType(XmlAccessType.FIELD)
public static class Message {
@XmlAttribute
@XmlJavaTypeAdapter(IDAdapter.class)
private Integer id = 0;
}
public static class IDAdapter extends XmlAdapter<Integer, Integer> {
private int counter = 1;
@Override
public Integer unmarshal(Integer v) throws Exception {
return v;
}
@Override
public Integer marshal(Integer v) throws Exception {
return counter++;
}
}
@XmlRootElement(name = "Messages")
@XmlAccessorType(XmlAccessType.FIELD)
public static class Messages {
@XmlElement(name = "Message")
private List<Message> messages = new ArrayList<Message>();
public List<Message> getMessages() {
return messages;
}
}
}