【Java】【XML】【JAXB】 サンプルプログラム(XML入力) [3]

JAXB 入力[3]

【「Java SE 6完全攻略」第73回 JAXB その1】
http://itpro.nikkeibp.co.jp/article/COLUMN/20080530/305406/?ST=develop&P=3
を作成していたら、以下のようなエラー。

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"persons" ). Expected elements are <{http://xml.javainthebox.net}person>,<{http://xml.javainthebox.net}persons>

 相当はまったが、「artists.xml(読む込むデータ)」を以下のように、「xmlns="http://xml.javainthebox.net"」を追記すれば、動作するようになった。

修正前

<persons >

修正後

<persons xmlns="http://xml.javainthebox.net" >

サンプル

以下、コードです。(若干修正している)

artists.xml(読む込むデータ)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persons xmlns="http://xml.javainthebox.net" >
  <person name="Neil Young" age="62" sex="MALE" />
  <person name="Bob Dylan" age="67" sex="MALE" />
  <person name="Joni Mitchell" age="65" sex="FEMALE" />
</persons>

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);
    }
}