编组时可选的 JAXB xml 属性 [英] optional JAXB xml attribute while marshalling

查看:36
本文介绍了编组时可选的 JAXB xml 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 JAXB 编组 java 对象时,我遇到了 xml 元素

When I marshal java object using JAXB I am getting below xml element

<error line="12" column="" message="test" />

但我想要xml如下

<error line="12" message="test" />

如果列值为空,那么我需要获取如上所示的 xml,否则我需要获取元素中的列属性.

If column value is empty then I need to get the xml as shown above otherwise I need to get the column attribute in the element.

有什么办法可以得到吗?

Is there any way to get it?

推荐答案

如果相应的字段/属性包含空的 String<,则属性只会被编组为空的 String 值/代码> 值.如果值为 null,则不会编组该属性.

An attribute will only be marshalled out with an empty String value if the corresponding field/property contains a empty String value. If the value is null the attribute will not be marshalled.

根目录

package forum13218462;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Root {

    @XmlAttribute
    String attributeNull;

    @XmlAttribute
    String attributeEmpty;

    @XmlAttribute(required=true)
    String attributeNullRequired;

}

演示

package forum13218462;

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Root root = new Root();
        root.attributeNull = null;
        root.attributeEmpty = "";
        root.attributeNullRequired = null;

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root attributeEmpty=""/>

这篇关于编组时可选的 JAXB xml 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆