How to ignore a field in castor marshalling

1.5k Views Asked by At

I'm using castor to create XML file from java object. I would like to ignore a field in my class when I create XML file.

The documentation http://castor.codehaus.org/reference/1.3.0/html/XML%20data%20binding.html says:

1.2.2.1. Marshalling Behavior
For Castor, a Java class has to map into an XML element. When Castor marshals an object, it will:
- use the mapping information, if any, to find the name of the element to create
or
- by default, create a name using the name of the class
It will then use the fields information from the mapping file to determine how a given property of the object has to be translated into one and only one of the following:
- an attribute
- an element
- text content
- nothing, as we can choose to ignore a particular field

But how, can I put annotation @IgnoreFields or something like that ? I know, it is possible to create mapping file to specify fields to be converted.

1

There are 1 best solutions below

1
On

Castor ignores fields that aren't specified in the mapping file by default.

Example: (Given an object and the mapping as below)

Object containing 2 fields while mapping file only specifies mapping for 1 of the field only.

  public class TestObj {
String param1;
String param2;

public String getParam1() {
    return param1;
}
public void setParam1(String param1) {
    this.param1 = param1;
}
public String getParam2() {
    return param2;
}
public void setParam2(String param2) {
    this.param2 = param2;
}}

Mapping File (test-mapping.xml)

<mapping>
<class name="TestObj">
    <map-to />
    <field name="param1" type="java.lang.String">
        <bind-xml name="param1" node="element" />
    </field>
</class>
</mapping>

Test code to print xml

    Marshaller marshaller = new Marshaller();
    Mapping mapping = new Mapping();
    mapping.loadMapping("test-mapping.xml");
    marshaller.setMapping(mapping);
    TestObj obj = new TestObj();
    StringWriter writer = new StringWriter();
    obj.setParam1("1");
    obj.setParam2("2");

    marshaller.setWriter(writer);
    marshaller.marshal(obj);

    System.out.println("output:"+writer.toString());

End Result

<test-obj>
<param1>1</param1>
</test-obj>