JAXB按原样使用字符串

JAXB按原样使用字符串,jaxb,jaxb2,Jaxb,Jaxb2,我使用REST,我想知道是否可以告诉jaxb在输出xml中插入一个字符串字段“原样”。 当然,在返回之前我会先打开包装,但我想保存这一步 @XmlRootElement(name="unnestedResponse") public class Response{ @Insert annotation here ;-) private String alreadyXml; private int otherDate; ... } 是否有可能告诉JAXB按原样使用字符串而不转义?我希望客户

我使用REST,我想知道是否可以告诉jaxb在输出xml中插入一个字符串字段“原样”。 当然,在返回之前我会先打开包装,但我想保存这一步

@XmlRootElement(name="unnestedResponse")
public class Response{
 @Insert annotation here ;-)
 private String alreadyXml;
 private int otherDate; ...
}
是否有可能告诉JAXB按原样使用字符串而不转义?我希望客户端不必解析我的响应,然后解析这个字段

您好,
m

您可以使用
@xmlanyement
并指定
DomHandler
来将XML文档的一部分保留为
字符串

客户

import javax.xml.bind.annotation.*;
@XmlRootElement
公共类客户{
私人字符串bio;
@XmlAnyElement(BioHandler.class)
公共字符串getBio(){
回归生物;
}
公共void setBio(字符串bio){
this.bio=bio;
}
}
BioHandler

import java.io.*;
导入javax.xml.bind.ValidationEventHandler;
导入javax.xml.bind.annotation.DomHandler;
导入javax.xml.transform.Source;
导入javax.xml.transform.stream.*;
公共类BioHandler实现DomHandler{
私有静态最终字符串BIO_START_TAG=“”;
私有静态最终字符串BIO_END_TAG=“”;
私有StringWriter xmlWriter=新StringWriter();
公共StreamResult createUnmarshaller(ValidationEventHandler errorHandler){
返回新的StreamResult(xmlWriter);
}
公共字符串getElement(StreamResult rt){
字符串xml=rt.getWriter().toString();
int beginIndex=xml.indexOf(BIO_START_标记)+BIO_START_标记.length();
int endIndex=xml.indexOf(BIO_END_标记);
返回xml.substring(beginIndex,endIndex);
}
公共源封送处理程序(字符串n,ValidationEventHandler errorHandler){
试一试{
字符串xml=BIO_START_标记+n.trim()+BIO_END_标记;
StringReader xmlReader=新的StringReader(xml);
返回新的StreamSource(xmlReader);
}捕获(例外e){
抛出新的运行时异常(e);
}
}
}
了解更多信息

以下的答案对我不起作用,因为当文本包含“&字符时(例如在URL中或使用HTML实体,例如“”),我在编组过程中遇到错误

通过将自定义
DomHandler
marshal
方法更改为

public Source marshal(String et, ValidationEventHandler veh) {
    Node node = new SimpleTextNode(et);
    return new DOMSource(node);
}
其中,
SimpleTextNode
实现如下节点接口:

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:我很想把这作为对博恩回答的评论,但不幸的是,我的名声太小了:-(

如果您使用它进行封送并使用标准JAXB,则可能重复一条重要说明:您必须传入org.w3c.dom.Element接口的实现,而不是像本例中那样传入字符串。否则,JAXB将不使用DOMDhandler进行封送。该实现实际上不必做任何事情非常有用,因此您可以在其中存储字符串,然后在封送处理方法中将其取出,并按照上面的示例进行后续操作,但它必须是对象实现元素的实例。@Gabriel-这是标准JAXB。JAXB引用实现中可能存在错误。@BlaiseDoughan您应该使用
int-endIndex=xml.lastIndexOf(BIO_END_TAG);
允许在xml字符串中使用标记。