JAXB按原样使用String [英] JAXB use String as it is

查看:64
本文介绍了JAXB按原样使用String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用REST,我想知道我是否可以告诉jaxb将字符串字段as-it-is插入到传出的xml中。
当然我会在返回之前将其解包,但我想保存此步骤。

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 like to save this step.

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

是否有可能告诉JAXB只使用String作为它没有逃脱?我希望客户端不必解析我的响应,然后解析此字段。

Is there a possability to tell JAXB to just use the String as it is without escapting? I want that the client does not have to parse my response and then parse this field.

问候,
m

推荐答案

你可以使用 @XmlAnyElement 并指定 DomHandler 以将XML文档的一部分保存为 String

You can use the @XmlAnyElement and specify a DomHandler to keep a portion of the XML document as a 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;
    }

}

BioHandler

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);
        }
    }

}

更多信息

  • http://blog.bdoughan.com/2011/04/xmlanyelement-and-non-dom-properties.html

这篇关于JAXB按原样使用String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆