Search code examples
jaxbjaxb2-basics

convert JAXBElement<String> value to java string


I have a pojo class where return type of variable is JAXBElement<String>. I want to store it in a String. 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.


Solution

  • 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