Can you marshal an object without a parent tag?

I have a class below. When Marshalling, I would like to omit the "config" tag, is that possible?

@XmlRootElement(name = "config")
@XmlAccessorType(XmlAccessType.FIELD)
public static class Config {

        @XmlElement(name = "dry-run")
        protected Boolean dryRun;

        @XmlElementWrapper(name = "filters")
        @XmlElement(name = "filter")
        protected List<String> filters;

        public Boolean isDryRun() {
                return dryRun;
        }

        public void setDryRun(boolean dryRun) {
                this.dryRun = dryRun;
        }

        public List<String> getFilters() {
                return filters;
        }
}

      

Example:

Current output:

<Root>
  <config xmlns:wf="nspace">
    <dry-run>false</dry-run>
    <filters>
      <filter>
        myFilter
      </filter>
    </filters>
  </config>
</Root>

      

Desired output:

<Root>
    <dry-run>false</dry-run>
    <filters>
      <filter>
        myFilter
      </filter>
    </filters>
</Root>

      

UPDATE:

All I wanted to know was "can this ONLY be done with JAXB or not?". Just check this question (not the answer) , I didn't understand how it was playing with JAXB, and no root element was written. This is exactly what I want.

+3


source to share


1 answer


So, you want to marshal your object not to a single XML subtree, but to an XML fragment, that is, a list of siblings without a parent. I believe this cannot be achieved with Jaxb itself. But you can serialize to some intermediate form and handle that. For example, you can create your own SAX ContentHandler

and have handlers counting depth and only delegate events with a non-zero nesting depth.



class NoRoot extends XMLFilterImpl {

  private int depth;

  @Override public void startDocument() throws SAXException
  {
    depth = 0;
  }

  @Override public void startElement(String uri, String localName,
                                     String qName, Attributes atts)
    throws SAXException
  {
    if (depth != 0) super.startElement(uri, localName, qName, atts);
    ++depth;
  }

  @Override public void endElement(String uri, String localName,
                                   String qName)
    throws SAXException
  {
    --depth;
    if (depth != 0) super.endElement(uri, localName, qName);
  }

}

      

0


source