2

これは「PersonType」クラスの生成コードです。

package demo;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PersonType", propOrder = {
"name",
"address"
})
public class PersonType {

@XmlElement(name = "Name", required = true)
protected String name;
@XmlElement(name = "Address", required = true)
protected List<AddressType> address;

public String getName() {
    return name;
}


public void setName(String value) {
    this.name = value;
}


public List<AddressType> getAddress() {
    if (address == null) {
        address = new ArrayList<AddressType>();
    }
    return this.address;
}

}

これは「AddressType」クラスの生成コードです。

    package demo;

 import javax.xml.bind.annotation.XmlAccessType;
 import javax.xml.bind.annotation.XmlAccessorType;
 import javax.xml.bind.annotation.XmlElement;
 import javax.xml.bind.annotation.XmlSchemaType;
 import javax.xml.bind.annotation.XmlType;

 @XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "AddressType", propOrder = {
"number",
"street"
 })
public class AddressType {

@XmlElement(name = "Number")
@XmlSchemaType(name = "unsignedInt")
protected long number;
@XmlElement(name = "Street", required = true)
protected String street;


public long getNumber() {
    return number;
}


public void setNumber(long value) {
    this.number = value;
}


public String getStreet() {
    return street;
}

public void setStreet(String value) {
    this.street = value;
}

}

これは、アンマーシャルしたいxmlファイルです

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="C:\JAXB Demo\demo.xsd">
  <Name>Sharon Krisher</Name>
  <Address>
    <Street>Iben Gevirol</Street>
    <Number>57</Number>
  </Address>
<Address>
  <Street>Moshe Sharet</Street>
   <Number>89</Number>
  </Address>
</Person>

コードフォーアンアーコール

JAXBContext context = JAXBContext.newInstance(PersonType.class);
    Unmarshaller unmarshaller =context.createUnmarshaller();
    //unmarshaller.setValidating(true);
    PersonType person =(PersonType) unmarshaller.unmarshal(new File("C:\\Users\\sithi\\workspace\\TestJAXB\\src\\data.xml") );

このコードは例外を与えます:

Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"PersonType"). Expected elements are (none)
4

2 に答える 2