There are several help topi...">

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

There are several help topics for the problem, but I did not find a solution that solved my problem. I appreciate the guidance in solving the problem.

I tried to generate xml through the marshal, and below xml is what is generated from the code.

I need to work with the xml structure below:

<?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>

code

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

Class TestSubject

public class TestSubject {

    String firstName;
    String lastNAme;
    int ssn;

//getters and setters

}

// unmarshall code in my main class

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

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

Exception

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)
+4
source share
1 answer

It seems you are not showing us the real XML that you are trying to untie. The error you see will happen if your XML was in the form

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

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

instead

<?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>

<testSubject> node, <Test> node. <Test> node, .

+4

Source: https://habr.com/ru/post/1527264/


All Articles