I’m rather new to JAXB and have come across a problem which I can’t seem to fix.
If I have a simple XML file as follows.
<Root>
<Test>TestStuff</Test>
</Root>
I would like to create a class to handle “root” and another to handle “test”. I know normally you wouldn’t do this but for this example here’s the classes I created;
@XmlRootElement
class MyElement {
private String test;
@XmlElement(name="Test")
public String getTest() { return test; }
public void setTest(String test) { this.test = test; }
}
@XmlRootElement(name="Root")
class Root {
private MyElement myElement;
public MyElement getMyElement() { return myElement; }
public void setMyElement(MyElement myElement) { this.myElement = myElement; }
}
When I run the code below I always get null for myElement.
@Test
public void testJAXB() throws Exception {
InputStream xmlInputStream = new FileInputStream(new File(".\\files\\test1.xml"));
JAXBContext context = JAXBContext.newInstance(Root.class, MyElement.class);
Unmarshaller um = context.createUnmarshaller();
Root root = (Root) um.unmarshal(xmlInputStream);
Assert.assertTrue(root.getMyElement().getTest().equals("TestStuff"));
}
Could someone point me in the right direction regarding this?
Thanks.
You could do the following leveraging
@XmlElementand@XmlValue:Root
MyElement
For More Information
UPDATE
If you are using EclipseLink MOXy (I’m the tech lead) as your JAXB provider you can use the
@XmlPath(".")extension to map this use case.Root
MyElement
For More Information