我試圖實現所有的Java類來處理以下XML代碼片段:XML:JAXB映射Java對象和XML文檔
<party date="2012-09-30">
<guest name="Albert">
<drink>wine</drink>
</guest>
</party>
我已經寫了3類:
Party.java :
package li.mnet.www.java.xml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "party")
public class Party {
@XmlAttribute(name = "date")
private String partyDate;
public Party() {}
public String getPartyDate() {return partyDate;}
public void setPartyDate(String partyDate) {
this.partyDate = partyDate;
}
}
Guest.java:
package li.mnet.www.java.xml;
import javax.xml.bind.annotation.XmlElement;
public class Guests {
private String name;
public Guests() {}
public void setGuestName(String name) {this.name = name;}
@XmlElement(name = "name")
public String getGuestName() {return name;}
}
PartyRunner.java:
package li.mnet.www.java.xml;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class PartyRunner {
public static void main(String[] args) {
Party party = new Party();
Guests guest = new Guests();
party.setPartyDate("2012-09-03");
guest.setGuestName("Albert");
JAXBContext context;
try {
context = JAXBContext.newInstance(Party.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(party, System.out);
} catch (JAXBException e) {e.printStackTrace();}
}
}
運行的應用程序後,我獲得以下控制檯輸出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<party date="2012-09-03"/>
我有什麼改變,那類Guest.java被打印出來呢?
非常感謝您的支持!
非常感謝您的詳細解釋,它幫助了我! – user2852537