3

unmarshalling 中にこのトピックの予期しない要素エラーと非常によく似た問題がありますが、それでも例外を解決できません。XML と package-info の名前空間はまったく同じなので... それとも xsd ファイルが原因ですか?

Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.example.org/Uni", local:"Uni"). Expected elements are <{http://www.example.org/Uni}uni>

XML:

<?xml version="1.0" encoding="UTF-8"?>
<tns:Uni xmlns:tns="http://www.example.org/Uni" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/Uni Uni.xsd ">
  <tns:Semester>
    <tns:nr>1</tns:nr>
    <tns:datum>01.02.2012</tns:datum>
  </tns:Semester>
   <tns:Semester>
    <tns:nr>2</tns:nr>
    <tns:datum>01.02.2012</tns:datum>
  </tns:Semester>
</tns:Uni>

XSD

<complexType name="Uni">
    <choice>
        <element name="Semester" type="tns:Semester" maxOccurs="unbounded"></element>
    </choice>
</complexType>

<complexType name="Semester">
    <sequence>
        <element name="nr" type="int"></element>
        <element name="datum" type="string"></element>
    </sequence>
</complexType>

パッケージ情報

@javax.xml.bind.annotation.XmlSchema(
        namespace = "http://www.example.org/Uni", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package parserTest;

Uni.java

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Uni
{

    @XmlElement(name = "Semester")
    protected List<Semester>    semester;

    public List<Semester> getSemester()
    {
        if (this.semester == null)
        {
            this.semester = new ArrayList<Semester>();
        }
        return this.semester;
    }

}

アンマーシャリング

public static void main(String[] args) throws JAXBException
{
    ObjectFactory factoryForElementObjects = new ObjectFactory();
    List<Semester> semesterL = new ArrayList<Semester>();

    Uni uni = new Uni();
    uni.semester = semesterL;

    JAXBContext context = JAXBContext.newInstance(Uni.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    Uni un = (Uni) unmarshaller.unmarshal(new File("src/main/resources/Uni.xml"));
    List<Semester> semesterA = un.semester;
    System.out.println(semesterA.get(0).nr);
}
4

1 に答える 1

4

問題は、unmarshaller が element を期待してuniいるのに、 が見つかったことUniです。

Uni クラスの XML 要素名を設定すると、うまくいくはずです。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Uni")
public class Uni
{

    @XmlElement(name = "Semester")
    protected List<Semester>    semester;

    public List<Semester> getSemester()
    {
        if (this.semester == null)
        {
            this.semester = new ArrayList<Semester>();
        }
        return this.semester;
    }

}
于 2013-09-11T18:30:50.413 に答える