【问题标题】:Convert string to JAXBElement using Java使用 Java 将字符串转换为 JAXBElement
【发布时间】:2015-04-21 06:17:22
【问题描述】:

在将 String 对象转换为需要设置的 JAXBElement 字符串对象时遇到一些问题

这是我需要设置值的目标方法

public void setData(JAXBElement<String> value) {
    this.data = ((JAXBElement<String> ) value);
}

为此,我编写了类似这样的代码

 ObjectFactory factory = new ObjectFactory();
    JAXBElement<ApplicationIngestionRequest> jaxbElement =  new JAXBElement(
            new  QName(ApplicationIngestionRequest.class.getSimpleName()), ApplicationIngestionRequest.class, request);

    StringWriter writer = new StringWriter();
    JAXBContext context =  JAXBContext.newInstance(ApplicationIngestionRequest.class);
    context.createMarshaller().marshal(jaxbElement, writer);
    LOG.info("JAXBElement object :\n"+ writer.toString());
    Unmarshaller u = context.createUnmarshaller();
    JAXBElement<ApplicationIngestionRequest> o = (JAXBElement<ApplicationIngestionRequest>) u.unmarshal(new StringReader(writer));

日志给了我以下输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ApplicationIngestionRequest><BranchCode></BranchCode><SourceCode>0000005511</SourceCode></ApplicationIngestionRequest>

现在当我尝试将方法设置为

losRequest.setData(o.toString());

它不允许我将其设置为 JAXBElement 格式。任何想法将不胜感激。

【问题讨论】:

  • 1) 什么是o? 2) 为什么将value 转换为与声明它的类型相同的类型(这是不必要的)? 3) 在任何对象上调用toString() 都会返回一个......好吧,它返回一个字符串,而不是JAXBElement&lt;String&gt;。你到底想达到什么目的? 4)“它不允许我。”你得到什么错误?
  • @Seelenvirtuose 我已经更新了问题。我只想将该 XML 输出转换为 JAXBElement 字符串,以便可以在该方法中进行设置。

标签: java jaxbelement


【解决方案1】:

根据代码 sn-p [setData(JAXBElement value)] , setData ,接受 '(JAXBElement') 的实例。但是在这里,您试图设置一个字符串值 [losRequest.setData(o.toString())] 。在这里你必须设置一个 'JAXBElement' 的实例。这可能是问题所在。

【讨论】:

  • 您能告诉我如何将该 XML 对象转换为 JAXBElement String 对象吗?
  • 请试试这个,新的 JAXBElement(o.toString());
猜你喜欢
  • 2023-03-17
  • 2013-01-29
  • 2011-01-08
  • 2019-12-18
  • 2019-10-17
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
相关资源
最近更新 更多