JAXB use String as it is

前端 未结 2 1109
难免孤独
难免孤独 2020-12-01 22:40

I use REST and i was wondering if i can tell jaxb to insert a string field \"as-it-is\" into the outgoing xml. Certainly i count unpack it before returning, but i would lik

2条回答
  •  粉色の甜心
    2020-12-01 22:59

    Following bdoughan's answer did not work for me as I encountered errors during marshalling when the text contained the '& character (e.g. in URLs or when using HTML entities such as e.g. " ").

    I was able to resolve this by changing the custom DomHandler's marshal method to

    public Source marshal(String et, ValidationEventHandler veh) {
        Node node = new SimpleTextNode(et);
        return new DOMSource(node);
    }
    

    where SimpleTextNode implements the Node interface as follows:

    class SimpleTextNode implements Node {
        
        String nodeValue = "";
        
        @Override    
        public SimpleTextNode(String nodeValue) {
            this.nodeValue = nodeValue;
        }
        
        @Override
        public short getNodeType() {
            return TEXT_NODE;
        }
    
        // the remaining methods of the Node interface are not needed during marshalling
        // you can just use the code template of your IDE...
    
        ...
    }
    

    PS: I would have loved to leave this as a comment to bdoughan's answer, but unfortunately I have way too little reputation :-(

提交回复
热议问题