7

我使用 REST,我想知道是否可以告诉 jaxb 将字符串字段“按原样”插入到传出的 xml 中。当然,我会在返回之前将其解包,但我想保存这一步。

@XmlRootElement(name="unnestedResponse")
public class Response{
 @Insert annotation here ;-)
 private String alreadyXml;
 private int otherDate; ...
}

是否有可能告诉 JAXB 只使用字符串而不转义?我希望客户端不必解析我的响应然后解析该字段。

问候,米

4

2 回答 2

11

您可以使用@XmlAnyElement并指定 aDomHandler将 XML 文档的一部分保留为String.

顾客

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Customer {

    private String bio;

    @XmlAnyElement(BioHandler.class)
    public String getBio() {
        return bio;
    }

    public void setBio(String bio) {
        this.bio = bio;
    }

}

生物处理器

import java.io.*;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.stream.*;

public class BioHandler implements DomHandler<String, StreamResult> {

    private static final String BIO_START_TAG = "<bio>";
    private static final String BIO_END_TAG = "</bio>";

    private StringWriter xmlWriter = new StringWriter();

    public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
        return new StreamResult(xmlWriter);
    }

    public String getElement(StreamResult rt) {
        String xml = rt.getWriter().toString();
        int beginIndex = xml.indexOf(BIO_START_TAG) + BIO_START_TAG.length();
        int endIndex = xml.indexOf(BIO_END_TAG);
        return xml.substring(beginIndex, endIndex);
    }

    public Source marshal(String n, ValidationEventHandler errorHandler) {
        try {
            String xml = BIO_START_TAG + n.trim() + BIO_END_TAG;
            StringReader xmlReader = new StringReader(xml);
            return new StreamSource(xmlReader);
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

}

了解更多信息

于 2012-10-29T14:10:57.530 回答
2

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

我能够通过将 customDomHandlermarshal方法更改为来解决这个问题

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

其中SimpleTextNode实现Node接口如下:

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

于 2020-07-31T10:46:10.297 回答