gpt4 book ai didi

attributes - 如何在 jaxb 编码期间跳过空字段

转载 作者:行者123 更新时间:2023-12-02 08:37:21 24 4
gpt4 key购买 nike

marshaller 有没有办法生成一个新的 xml 文件,跳过任何空属性?所以
像 someAttribute=""之类的东西没有出现在文件中。

谢谢

最佳答案

A JAXB (JSR-222)实现不会编码(marshal)用 @XmlAttribute 注释的字段/属性包含空值。

Java 模型(根)

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Root {

private String foo;
private String bar;

@XmlAttribute
public String getFoo() {
return foo;
}

public void setFoo(String foo) {
this.foo = foo;
}

@XmlAttribute(required=true)
public String getBar() {
return bar;
}

public void setBar(String bar) {
this.bar = bar;
}

}

演示代码

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.setFoo(null);
root.setBar(null);

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

}

输出

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

关于attributes - 如何在 jaxb 编码期间跳过空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20013486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com