简体   繁体   English

JAXB 编组器使用 Java 成员变量约定

[英]JAXB marshaller using Java member variable convention

I'm currently trying to figure out why JAXB marshaller uses Java member variable convention as opposed to follow the XmlType annotation.我目前正试图弄清楚为什么 JAXB 编组器使用 Java 成员变量约定而不是遵循 XmlType 注释。

Here's the situation:情况如下:

  • Third-party gave us XSD第三方给我们 XSD
  • We use JDK tools to generate Java classes我们使用JDK工具生成Java类
  • The generated Java classes produced correct annotation: @XmlType(name = "XML_DOCUMENT_TYPE")生成的 Java 类产生了正确的注释:@XmlType(name = "XML_DOCUMENT_TYPE")

But when I tried to marshal the class back to XML, JAXB converts it to <xmlDocumentType> instead of <XML_DOCUMENT_TYPE>但是当我尝试将 class 编组回 XML 时,JAXB 将其转换为<xmlDocumentType>而不是<XML_DOCUMENT_TYPE>

Any idea why?知道为什么吗? (If so, how can I fix this?) (如果是这样,我该如何解决这个问题?)

Update: to clarify, the issue occurred at the top/root level element, not at the sub element/member variable.更新:澄清一下,问题发生在顶级/根级别元素,而不是子元素/成员变量。

UPDATE (based on comment by xandross更新(基于 xandross 的评论

You can use @XmlRootElement to control the root element name:您可以使用@XmlRootElement来控制根元素名称:

@XmlRootElement(name="XML_DOCUMENT_TYPE")
public class Foo {
  ...
}

Alternatively you can wrap the root object in an instance of JAXBElement to supply root element information.或者,您可以将根 object 包装在JAXBElement实例中以提供根元素信息。


UPDATE (based on comment by Mohamed Mansour)更新(基于 Mohamed Mansour 的评论)

In JAXB classes correspond to XML types, and fields/properties correspond to XML attributes/elements.在 JAXB 中,类对应于 XML 类型,字段/属性对应于 XML 属性/元素。 This makes sense when you consider there may exist an address type:当您考虑可能存在地址类型时,这是有道理的:

<xs:complexType name="address">
    <xs:sequence>
        <xs:element name="street" type="xs:string"/>
    </xs:sequence>
</xs:complexType>

and multiple elements (with different names) that are of that type:以及属于该类型的多个元素(具有不同的名称):

<xs:complexType name="customer">
    <xs:sequence>
        <xs:element name="billing-address type="address"/>
        <xs:element name="shipping-address type="address"/>
    </xs:sequence>
</xs:complexType>

You can control the name of the element/attribute that a property maps to with the @XmlElement / @XmlAttribute annotations:您可以使用@XmlElement / @XmlAttribute注释控制属性映射到的元素/属性的名称:

@XmlElement(name="shipping-address")
public getShippingAddress() {
    return shippingAddress;
}

or或者

@XmlElement(name="ShippingAddress")
public getShippingAddress() {
    return shippingAddress;
}

If the property is not annotated it is treated as @XmlElement and the element name is derived from the property name.如果该属性没有注释,则将其视为@XmlElement ,并且元素名称派生自属性名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM