标签云

微信群

扫码加入我们

WeChat QR Code

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;@XmlRootElementclass 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. @Testpublic 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.


Hi, thanks for this. Unfortunately, the MyElement class will eventually need to contain several elements. For example I may need to add <Other> element to the MyElement class: <Root> <Test>TestStuff</Test> <Other>random text</Other> </Root>

2019年05月23日54分34秒

Sorry - the class should have been called MyElements rather than the singular.

2019年05月24日54分34秒

user1197930 - I have updated my answer with how this could be done with the XmlPath extension in EclipseLink JAXB (MOXy).

2019年05月24日54分34秒

Thanks very much Blaise. I'm not currently using MOXy but i did notice the XmlPath annotation when searching the web for a solution to my problem. I does seem to give me the flexibility I need. I'll use this. Thanks again.

2019年05月24日54分34秒