【发布时间】:2012-01-19 12:31:30
【问题描述】:
您知道 xml 编辑器如何使您能够从 xsd 方案创建示例 xml,用随机的东西填充所有元素和属性。现在我只是得到空的根元素标签。是否可以使用 JAXB 编组 xml 并出于测试原因实现类似的目标? 我是 java 和 jaxb 的新手,不胜感激。
编辑。 根元素类代码:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"document",
"taskList",
"addDocuments",
"expansion",
"acknowledgement"
})
@XmlRootElement(name = "Header")
public class Header {
@XmlElement(name = "Document")
protected DocumentType document;
@XmlElement(name = "TaskList")
protected TaskListType taskList;
@XmlElement(name = "AddDocuments")
protected AddDocumentsType addDocuments;
@XmlElement(name = "Expansion")
protected ExpansionType expansion;
@XmlElement(name = "Acknowledgement")
protected AcknowledgementType acknowledgement;
@XmlAttribute(name = "time", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar time;
@XmlAttribute(name = "msg_type", required = true)
protected short msgType;
@XmlAttribute(name = "msg_id", required = true)
protected String msgId;
@XmlAttribute(name = "msg_acknow")
protected Short msgAcknow;
@XmlAttribute(name = "from_org_id", required = true)
protected String fromOrgId;
@XmlAttribute(name = "from_organization", required = true)
protected String fromOrganization;
@XmlAttribute(name = "from_department")
protected String fromDepartment;
@XmlAttribute(name = "from_sys_id", required = true)
protected String fromSysId;
@XmlAttribute(name = "from_system", required = true)
protected String fromSystem;
@XmlAttribute(name = "from_system_details")
protected String fromSystemDetails;
@XmlAttribute(name = "to_org_id")
protected String toOrgId;
@XmlAttribute(name = "to_organization", required = true)
protected String toOrganization;
@XmlAttribute(name = "to_department")
protected String toDepartment;
@XmlAttribute(name = "to_sys_id")
protected String toSysId;
@XmlAttribute(name = "to_system")
protected String toSystem;
@XmlAttribute(name = "to_system_details")
protected String toSystemDetails;
// getters n setters are omitted
}
创建 xml:
ObjectFactory objectFactory = new ObjectFactory();
Header header = objectFactory.createHeader();
JAXBContext jaxbContext = JAXBContext.newInstance(Header.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(header, file);
我得到了什么:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Header msg_type="0" />
其他东西在哪里?我可以在不创建所有元素和属性并手动设置值的情况下接收类似于完整 xml 的内容吗?
【问题讨论】:
-
我不是 100% 清楚你想要达到什么目的。是否希望将 JAXB 注释类与测试数据一起呈现为 XML?
-
现在我只是得到空的根元素标签,我想用一些测试数据填充所有嵌套元素和属性。
-
使用 schemagen 从您的 JAXB 注释 bean 生成 XSD,并要求您的 XML 编辑器从该 XSD 生成示例 XML。
-
但是我有一个 xsd,我用 xjc 从中生成了类。有没有办法在 java 代码中使用 jaxb 来做到这一点?
-
不幸的是,在你的情况下,没有办法“神奇地”得到你想要的。您将不得不编写代码....