@XmlTransient标记值在解组时返回null

时间:2013-01-09 09:17:41

标签: jaxb jaxb2

我正在使用@XmlTransient隐藏输出XML文件中的一些字符串。它在编组时工作正常,并且XML很好。
但是当我解组XML时,@XmlTransient标记的值显示为空。

1 个答案:

答案 0 :(得分:1)

@XmlTransient做什么

@XmlTransient将该属性标记为未映射,因此它将从编组和解组中排除。


你能做什么

如果您只想从编组中排除该值,可以考虑使用XmlAdapter

XmlAdapter(StringAdapter)

XmlAdapter将始终返回""进行编组操作,JAXB实现将返回一个空元素。如果您使用EclipseLink MOXy作为JAXB实现,则可以返回null以完全消除该节点(请参阅:http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html)。

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class StringAdapter extends XmlAdapter<String, String> {

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

    @Override
    public String unmarshal(String string) throws Exception {
        return string;
    }

}

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

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

    String name;

    String address;

    @XmlJavaTypeAdapter(StringAdapter.class)
    String password;

}

input.xml中

<Person>
    <name> some name </name>
    <password> some password </password>
    <address> some address </address>
</Person>

演示

import java.io.File;
import javax.xml.bind.*;

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum14231799/input.xml");
        Person person = (Person) unmarshaller.unmarshal(xml);

        System.out.println(person.password);

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

}

输出

 some password 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Person>
    <name> some name </name>
    <address> some address </address>
    <password></password>
</Person>