让我知道序列化Java对象下载的最佳方法。这是从WSDL的java wsimport工具生成的类。
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Download", propOrder = {
"Response",
"VendorInformation",
"DownloadItem",
"DownloadCommentItem",
"DownloadIntercomItem"
})
public class Download
{
@XmlElement(name = "Response")
protected ResponseMessageManagementType Response;
@XmlElement(name = "VendorInformation")
protected DownloadVendorInformation VendorInformation;
@XmlElement(name = "DownloadItem")
protected List<DownloadDownloadItem> DownloadItem;
@XmlElement(name = "DownloadCommentItem")
protected ArrayOfDownloadDldComment DownloadCommentItem;
@XmlElement(name = "DownloadIntercomItem")
protected ArrayOfDownloadDldIntercom DownloadIntercomItem;
.........................
}
从该工具生成的java类没有任何serlization实现。 我想按照这种格式序列化Download类:
<?xml version="1.0" encoding="utf-8"?>
<Download xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="HTTP://xyz.abc.Com//Vendor/DownloadWSE.xsd">
<Response>
.....
</Response>
<VendorInformation>
...............
</VendorInformation>
<DownloadItem>
<DownloadDownloadItem>
.......
</DownloadDownloadItem>
<DownloadDownloadItem>
.......
</DownloadDownloadItem>
<DownloadDownloadItem>
.......
</DownloadDownloadItem>
</DownloadItem>
<DownloadCommentItem>
........
</DownloadCommentItem>
<DownloadIntercomItem>
........
</DownloadIntercomItem>
</Download>
您可以看到XmlElementName与XML字符串内容之间的映射。 我对如何做到这一点感到茫然。
由于
答案 0 :(得分:2)
这是JAXB。你需要:
JAXBContext ctx = JAXBConetxt.newInstance(Download.class);
Marshaller m = ctx.createMarshaller();
m.marshal(downloadObject, out);
其中out
可以是很多内容,包括OutputStream
,Writer
和File
。如果您想将其作为String
,请使用StringWriter
答案 1 :(得分:1)
这是JAXB,要使您的示例正常工作,您需要提供根元素和命名空间信息:
根元素
当您使用JAXB封送对象时,它需要有关根元素的信息。一种方法是使用Download
@XmlRootElement
课程添加注释
@XmlRootElement(name="Download")
public class Download
如果你不能这样做,你需要将Download
的实例包裹在JAXBElement
中:
Download download = new Download();
QName qname = new QName("HTTP://xyz.abc.Com//Vendor/DownloadWSE.xsd";
JAXBElement<Download> jaxbElement = new JAXBElement(qname, "Download"), Download.class, download);
命名空间资格
另外,要获得命名空间限定,您可以使用包级别@XmlSchema
注释:
@XmlSchema(
namespace="HTTP://xyz.abc.Com//Vendor/DownloadWSE.xsd",
elementFormDefault=XmlNsForm.QUALIFIED)
package your.model.package.containing.download;
import javax.xml.bind.annotation.*;
<强>演示强>
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Download.class);
Download download = new Download();
QName qname = new QName("HTTP://xyz.abc.Com//Vendor/DownloadWSE.xsd";
JAXBElement<Download> jaxbElement = new JAXBElement(qname, "Download"), Download.class, download);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(jaxbElement, System.out);
}
}