Search code examples
javaserializationxml-serializationxstream

Remove/Replace/Combine tag generated from parent List<> object in XStream


I'm using XStream to convert java objects to their XML counterparts.

One such object contains a List<Window> windows variable, which when generated displays:

<windows>
    <Window>
                  <WindowType>Monthly</WindowType>
                  <WindowBegin>
                    <Month>null</Month>
                    <Day>null</Day>
                  </WindowBegin>
                  <WindowEnd>
                    <Month>null</Month>
                    <Day>null</Day>
                  </WindowEnd>
    </Window>
    <Window>
    ....
    </Window>
</windows>

I would like to know if it's possible to prevent the List<> parent tag from being generated, like so:

        <Window>
                      <WindowType>Monthly</WindowType>
                      <WindowBegin>
                        <Month>null</Month>
                        <Day>null</Day>
                      </WindowBegin>
                      <WindowEnd>
                        <Month>null</Month>
                        <Day>null</Day>
                      </WindowEnd>
        </Window>
        <Window>
        ....
        </Window>

This question uses string.replace, but this will leave gaps in the xml if this list is within another object that need to be cleaned. Speed is of top priority for this, so I was looking for an approach from within XStream itself if possible.

Thanks


Solution

  • It's possible that I didn't word the question correctly, but the solution I found (through XStream) doesn't exactly remove the tag, but uses implicit naming to combine the parent tag with its children. Thanks to @Blaise Doughan's excellent tutorials for this.

    Ex)

    List windows; Will serialize to:

    <windows>
        <Window>
                      <WindowType>Monthly</WindowType>
                      <WindowBegin>
                        <Month>null</Month>
                        <Day>null</Day>
                      </WindowBegin>
                      <WindowEnd>
                        <Month>null</Month>
                        <Day>null</Day>
                      </WindowEnd>
        </Window>
        <Window>
        ....
        </Window>
    </windows>
    

    But adding:

    @XStreamImplicit(itemFieldName="Window")
    List<Window> windows;
    

    will serialize to:

            <Window>
                          <WindowType>Monthly</WindowType>
                          <WindowBegin>
                            <Month>null</Month>
                            <Day>null</Day>
                          </WindowBegin>
                          <WindowEnd>
                            <Month>null</Month>
                            <Day>null</Day>
                          </WindowEnd>
            </Window>
            <Window>
            ....
            </Window>