JAXBContextを使用したXMLの読み書きクラスと、
XMLSchemaのサンプルです。
XMLSchemaファイルをXJCでコンパイルしておくこと
XmlReader.java
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.hoge.xml.MemberList; public class XmlReader { private String filename; private JAXBContext jaxbc; XmlReader(String xmlFileName) throws JAXBException { this.filename = xmlFileName; jaxbc = JAXBContext.newInstance(MemberList.class); } public MemberList readListXml() throws JAXBException, IOException { InputStream listIs = new FileInputStream(filename); Unmarshaller um = jaxbc.createUnmarshaller(); MemberList list = (MemberList) um.unmarshal(listIs); listIs.close(); return list; } public void writeListXml(MemberList getList) throws JAXBException, IOException { OutputStream os = new FileOutputStream(filename); Marshaller mu = jaxbc.createMarshaller(); mu.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); mu.marshal(getList, os); os.close(); } }
memberList.xsd
<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="memberList"> <xsd:complexType> <xsd:sequence minOccurs="1" maxOccurs="unbounded"> <xsd:element name="member" type="memberType" /> </xsd:sequence> <xsd:attribute ref="listName" /> </xsd:complexType> </xsd:element> <xsd:complexType name="memberType"> <xsd:sequence> <xsd:element ref="name" /> <xsd:element ref="joinDate" /> <xsd:element ref="url" /> <xsd:element ref="comment" /> </xsd:sequence> </xsd:complexType> <xsd:element name="name" type="xsd:string" /> <xsd:element name="joinDate" type="xsd:date" /> <xsd:element name="url" type="xsd:anyURI" /> <xsd:element name="comment" type="xsd:string" /> <xsd:attribute name="listName" type="xsd:string" /> </xsd:schema>
やっつけです。はい