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

UnMarshalException:意外元素(URI:“”,本地:“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>

只要纠正一下就行了。

正如stacktrace所说的

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

您将获得一个 节点,而您需要一个 节点。因为 是根节点,所以它发生在那里。

 类似资料: