tags:

views:

159

answers:

2

I have the following field in my class:

private List<String> messages;

Here's the mapping I have:

<field name="messages" collection="arraylist" type="string" container="false>
  <bind-xml name="errors" node="element"/>
</field>

This is what I get as a result of marshalling:

<errors><string>message1</string><string>message2</string></errors>

And this is what I want to achieve:

<errors><error>message1</error><error>message2</error></errors>

Any help is appreciated!

A: 

Is there any reason you are using Marshalling to achieve this? It will have a set way of defining the XML output so that it knows how to recreate the objects when unmarshalling. So if you really want that XML output using marshalling I think you would need to create a new type called Error and your list would be:

private List<Error> messages;

And the mapping:

<field name="messages" collection="arraylist" type="error" container="false>
  <bind-xml name="errors" node="element"/>
</field>

Alternatively, if you are just looking to create xml output and your content really is as simple as what you have given above then you could just write a toXml() method which loops through the list adding the content exactly as you want it. The inverse can be done with a fromXml() method that parses the XML using DOM or SAX and rebuilds the list of strings.

DaveJohnston
Thank you, Dave, for confirming my findings that what I want can't be done with Castor. In our project we use Castor to render XML views (domain object -> XML). Usually our content is not as simple, I was just adding a mapping for an object that carried error messages which are presented to the user.I still can't believe something this simple cannot be done!
Dmitriy
A: 

Why not use JAXB?

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

    @XmlRootElement
    public class Errors {

        private List<String> messages;

        @XmlElement(name="error")
        public List<String> getMessages() {
            return messages;
        }

        public void setMessages(List<String> messages) {
            this.messages = messages;
        }

    }

If you like an external binding file you can use EclipseLink JAXB (MOXy):

<?xml version="1.0" encoding="UTF-8"?>
<xml-bindings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"&gt;
    <java-types>
        <java-type name="Errors">
            <xml-root-element/>
            <java-attributes>
                <xml-element java-attribute="messages" name="error"/>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>
Blaise Doughan