gpt4 book ai didi

java - 如何获取 XmlType 的字符串表示形式?

转载 作者:太空狗 更新时间:2023-10-29 22:44:29 26 4
gpt4 key购买 nike

是否可以将 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 注释。有什么办法解决这个问题吗?

最佳答案

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

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

String xmlString = sw.toString();

关于java - 如何获取 XmlType 的字符串表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6032066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com