person.xsd(定義ファイル)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsd:schema version="1.0"
targetNamespace="http://xml.javainthebox.net"
xmlns:tns="http://xml.javainthebox.net"
xmlns:xsd="">http://www.w3.org/2001/XMLSchema">
<xsd:element name="persons">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="tns:person" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="person">
<xsd:complexType>
<xsd:attribute name="name" type="xsd:string"/>
<xsd:attribute name="age" type="xsd:int"/>
<xsd:attribute name="sex" type="tns:sex"/>
</xsd:complexType>
</xsd:element>
<xsd:simpleType name="sex">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="MALE"/>
<xsd:enumeration value="FEMALE"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
sampleMain.java(メイン)
import converter.*;
public class sampleMain {
public static void main(String args[]) {
sampleConvertXmlToPdf obj = new sampleConvertXmlToPdf();
try {
obj.sampleConvertXml(
".\\src\\artists.xml",
".\\src\\output\\out.xml",
"net.javainthebox.xml" );
} catch (Exception ex) {
System.out.println("False ... \n" + ex);
return;
}
System.out.println("Success!!" );
}
}
sampleConvertXml.java
package converter;
import net.javainthebox.xml.Person;
import net.javainthebox.xml.Persons;
import common.UnmarshallerSample;
public class sampleConvertXmlToPdf {
public sampleConvertXmlToPdf() {
}
public void convertXml(
String inputFilePath, String outputFilePath, String spaceName)
throws Exception {
UnmarshallerSample obj = new UnmarshallerSample();
Persons artists
= (Persons)obj.Unmarshaller(inputFilePath, spaceName);
// 出力
for (Person person: artists.getPerson()) {
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("Sex: " + person.getSex());
System.out.println("" );
}
}
}
UnmarshallerSample.java
package common;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class UnmarshallerSample {
public UnmarshallerSample() {
}
/**
* XMLファイルを読み込みにオブジェクトを返す。
*
* @param inputFilePath 入力するXMLファイルのパス(絶対パス)
* @param spaceName 名前空間
* @return Object
* @exception javax.xml.bind.UnmarshalException 不正なXMLなどに起こりうる例外。
* @see
* @version 0.0.1
*/
public Object Unmarshaller(String inputFilePath, String spaceName)
throws JAXBException {
// 1. JAXBContextオブジェクトの生成
// 引数はパッケージ(名前空間)もしくはクラス
JAXBContext context
= JAXBContext.newInstance(spaceName);
// 2. Unmarsallerオブジェクトの取得
Unmarshaller unmarshaller = context.createUnmarshaller();
File inputFile = new File(inputFilePath);
// 3. アンマーシャリング
// 戻り値はルートタグに相当するオブジェクト
return unmarshaller.unmarshal(inputFile);
}
}