convert JAXBElement<String> value to java string

Pyntamil Selvi picture Pyntamil Selvi · Dec 8, 2015 · Viewed 23.4k times · Source

I have a pojo class where return type of variable is JAXBElement<String>. I want to store it in a java string.Could. Can someone explain how to do it?

File file = new File("C:/Users/Admin/Desktop/JubulaXMLFiles/DemoWithDrools_1.0.xml");    

        JAXBContext jaxbContext = JAXBContext.newInstance(Content.class);    

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();    

        Content e=(Content) jaxbUnmarshaller.unmarshal(file);    
        String retrivedValue = (String)e.getProject().getName().toString();
        System.out.println(retrivedValue);

Output is like javax.xml.bind.JAXBElement@5a99da. But I want to retrieve the string value in retrivedValue.

Answer

SubOptimal picture SubOptimal · Feb 29, 2016

If getProject() returns the type JAXBElement<String> then getName() returns the name of the XML tag. To get the value of that element you need to call getValue().

Find below a small snippet

QName qualifiedName = new QName("", "project");
JAXBElement<String> project = new JAXBElement<>(qualifiedName, 
        String.class, null, "funnyCoding");
System.out.printf("getName()  - %s%n", project.getName());
System.out.printf("getValue() - %s%n", project.getValue());

output

getName()  - project
getValue() - funnyCoding