1

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

4

1 回答 1

1

@XmlTransient做什么

@XmlTransient将该属性标记为未映射,因此它被排除在编组和解组之外。


你能做什么

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

XmlAdapter(字符串适配器)

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;

}

输入.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>
于 2013-01-09T10:46:11.437 回答