简体   繁体   English

解组空的xml元素jaxb

[英]Unmarshalling empty xml element jaxb

I have an empty tag like this <tagName/> . 我有一个像这样的空标签<tagName/> When I unmarshalling it if this property is the type of long or float it is null. 当我解组它时,如果此属性是long或float类型,则为null。 But if this property is the type of string, the property is tagName = ''; 但是,如果此属性是字符串的类型,则该属性为tagName = ''; . And after marshalling is <tagName></tagName> . 编组后是<tagName></tagName> How can I set empty tag name which is string java property to null while unmarshalling? 解组时,如何将字符串java属性的空标记名设置为null?

There are (at least) 2 ways to do this. 有(至少)两种方法可以执行此操作。

  1. If the classes are yourself and not auto-generated from xsd or similar you can use an adapter. 如果这些类是您自己的,并且不是从xsd或类似的类自动生成的,则可以使用适配器。

For example a class Cart: 例如一个购物车类:

@XmlRootElement(name = "Cart")
@XmlAccessorType(XmlAccessType.FIELD)
public class Cart {

    @XmlJavaTypeAdapter(EmptyTagAdapter.class)
    protected String tagName;
}

can use an adapter like below: 可以使用如下适配器:

public class EmptyTagAdapter extends XmlAdapter<String, String> {

    @Override
    public String marshal(String arg0) throws Exception {
        return arg0;
    }

    @Override
    public String unmarshal(String arg0) throws Exception {
       if(arg0.isEmpty()) {
           return null;
       }
        return arg0;
    }
}

For an xml that looks like this: 对于如下所示的xml:

<Cart>
  <tagName/>
</Cart>

You would get the empty tagName as null. 您将获得空的tagName作为null。

  1. If your classes are generated from an xsd you could mention that the field can be nillable. 如果您的类是从xsd生成的,则可以提及该字段可以为nillable。

For example as below: 例如如下:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.1">
    <xs:element name="Cart">
        <xs:complexType>
            <xs:all>
                <xs:element name="tagName" type="xs:string" nillable="true" />
            </xs:all>
        </xs:complexType>
    </xs:element>
</xs:schema>

and then you would need to have in your xml with the empty element xsi:nil="true" as this example: 然后您需要在xml中使用空元素xsi:nil =“ true”作为此示例:

<Cart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <tagName/>
  <tagName xsi:nil="true" />
</Cart>

It would have the same result, the value as null. 它将具有相同的结果,该值为null。

The use of the adapter is more to my liking but depends on your case. 我更喜欢使用适配器,但要视您的情况而定。 Hopefully one of the cases covers you. 希望其中一种情况能涵盖您。

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

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