【问题标题】:How to get String representation of XmlType?如何获取 XmlType 的字符串表示形式?
【发布时间】:2011-08-27 06:52:24
【问题描述】:

是否可以将 javax.xml.bind.annotation.XmlType 转换为 XML 的字符串表示形式?

例子:

以下类 Req 来自第三方库,因此我无法覆盖 toString() 方法。

@javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
@javax.xml.bind.annotation.XmlType(name = "req", propOrder = {"myDetails", "customerDetails"})
public class Req  {
...
}

在我的应用程序中,我想简单地获取 XML 的字符串表示,以便我可以将其记录到文件中:

<Req>
    <MyDetails>
    ...
    </MyDetails>
    <CustomerDetails>
    ...
    </CustomerDetails>
</Req>

当我尝试使用 JAXB 和 Marshall 转换为 XML 字符串时:

JAXBContext context = JAXBContext.newInstance(Req.class);
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(instanceOfReq, sw);
String xmlString = sw.toString();

我得到以下异常:

javax.xml.bind.MarshalException
    - with linked exception:
    [com.sun.istack.SAXException2: unable to marshal type "mypackage.Req" as an element because it is missing an @XmlRootElement annotation]

我查看了第三方库中的其他类,它们都没有使用@XmlRootElement 注释。有什么办法吗?

【问题讨论】:

    标签: java xml jaxb


    【解决方案1】:

    您可以使用 JAXB 并将其编组为 xml 字符串

    JAXBContext context = JAXBContext.newInstance(Req.class);
    Marshaller marshaller = context.createMarshaller();
    StringWriter sw = new StringWriter();
    marshaller.marshal(instanceOfReq, sw);
    
    String xmlString = sw.toString();
    

    【讨论】:

    • 对 OP 的警告:JAXBContexts 的创建成本很高(速度很慢)。创建并重用单个实例。
    • 尝试使用 JAXB 和 Marshall,但得到了上述帖子中描述的 MarshalException。
    • 并且不能更改类 Req 以添加 XmlRoot 注释?
    • 不,很遗憾没有 - 它包含在第三方库中。
    • 好的,试试这个marshaller.marshal(new JAXBElement( new QName("","Req"),Req.class,instanceOfReq), sw);
    【解决方案2】:

    除了 Bala R 指出的内容之外,如果您的 JAXB 元素没有 @xmlrootelement,您可以执行此操作

    JAXBContext context = JAXBContext.newInstance(YourClass.class);
                Marshaller marshaller = context.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                StringWriter sw = new StringWriter();
                JAXBElement jx = new JAXBElement(new QName("YourRootElement"), YourClass.class, input);
                marshaller.marshal(jx, sw);
                String xmlString = sw.toString();
    

    这也是here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-23
      • 2020-01-14
      • 2015-09-30
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多