当前位置: 首页 > 知识库问答 >
问题:

UnmarshalException:意外元素(URI:“”,local:“TestSubject”)。需要的元素为

郑理
2023-03-14
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Test>
    <testSubject>
        <firstName>test1</firstName>`enter code here`
        <lastNAme>lastname</lastNAme>
        <ssn>123456</ssn>
    </testSubject>
</Test>
@XmlRootElement(name = "Test")
public class Test { 
      public Test()
      {
          testSubject = new ArrayList<TestSubject>();
      }

    List<TestSubject> testSubject;

    @XmlElement(name = "testSubject", type = TestSubject.class)         
    public List<TestSubject> getTestSubject() {
        return testSubject;
    }

    public void setTestSubject(List<TestSubject> testSubject) {
        this.testSubject = testSubject;
    }
public class TestSubject {

    String firstName;
    String lastNAme;
    int ssn;

//getters and setters

}

//我的主类中的解马歇尔代码

JAXBContext jc = JAXBContext.newInstance(Test.class);

Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("c://testSubjects.xml");
Test tests = (Test) unmarshaller.unmarshal(xml);

例外

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"TestSubject"). Expected elements are <{}Test>
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:662)

共有1个答案

司徒浩思
2023-03-14

您似乎没有向我们展示您试图解封的真正XML。如果XML格式为

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<testSubject>
    <firstName>test1</firstName>
    <lastNAme>lastname</lastNAme>
    <ssn>123456</ssn>
</testSubject>

而不是

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Test>
    <testSubject>
        <firstName>test1</firstName>
        <lastNAme>lastname</lastNAme>
        <ssn>123456</ssn>
    </testSubject>
</Test>

简单纠正一下。

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"TestSubject"). Expected elements are <{}Test>
 类似资料: