Jaxb String from XML

631 views Asked by At

Using a Jaxb unmarshaller, I cannot achieve to load a XML content as a string.

Here is a running example of what I am trying to achieve.

public static class BarAdapter extends XmlAdapter<Object, String> {
    @Override
    public Object marshal(String v) throws Exception {
        return null;
    }

    @Override
    public String unmarshal(Object v) throws Exception {
        return null; // what to do with the ElementNsImpl??
    }

}

@XmlAccessorType(XmlAccessType.FIELD)
public static class Container implements Serializable {

    @XmlAnyElement
    @XmlJavaTypeAdapter(BarAdapter.class)
    private String bar;

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }
}

public static void main(String[] args) throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(Container.class);
    String xml = "<foo><bar><name>Barry</name><surName>White</surName></bar></foo>";
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    InputStream is = new ByteArrayInputStream(xml.getBytes());
    JAXBElement<Container> barWrapperElement = unmarshaller.unmarshal(new StreamSource(is), Container.class);
    Container container = barWrapperElement.getValue();

    System.out.println(container.getBar());
}

I would like to have into bar : <bar><name>Barry</name><surName>White</surName></bar>

I've tried to use the @XmlAnyElement but it gives a ElementNsImpl and I need a String.

1

There are 1 answers

0
Charles Follet On BEST ANSWER

If you have a better solution, please post. I am feeling that I am not doing it right.

I can transform ElementNsImpl into a String. So :

@Override
public String unmarshal(Object obj) throws Exception {
   // Be careful, affect a new string writer has to be done within your
   // unmarshaller. If you do this here, it will partially unmarshall. 
   // I can povide more code upon request
   StringWriter stringWriter = new StringWriter();

   TransformerFactory transformerFactory = TransformerFactory.newInstance();
   Transformer transformer = transformerFactory.newTransformer();
   
   Document document = ((Element) obj).getOwnerDocument();
   transformer .transform(new DOMSource(document), new StreamResult(stringWriter));

   return stringWriter.toString();
}