0

When generating a XML file with BeanIO, the StreamBuilder name is used as root element. How to suppress this root element?

Example:

StreamBuilder builder = new StreamBuilder("builder_name")
    .format("xml")
    .parser(new XmlParserBuilder()).addRecord(Test.class);

The Test class:

@Record
public class Test {

    @Field(at=0)
    private String field1 = "ABC";

    // Getters and Setters ...

}

The generated XML file:

<builder_name>
  <Test>
    <field1>ABC</field1>
  </Test>
</builder_name>

I don't want builder_name to be showed as root element. I want Test element to be the root. How can I achieve that?

1 Answers1

0

You need to set the xmlType property/attribute to XmlType.NONE on your stream configuration.

The answer is in Appendix A - XML Mapping file reference of the documentation.

xmlType - The XML node type mapped to the stream. If not specified or set to element, the stream is mapped to the root element of the XML document being marshalled or unmarshalled. If set to none, the XML input stream will be fully read and mapped to a child group or record.

The trick is now to translate that piece of information into the StreamBuilder API, which is:

xmlType(XmlType.NONE)

Your example then becomes:

StreamBuilder builder = new StreamBuilder("builder_name")
  .format("xml")
  .xmlType(XmlType.NONE)
  .parser(new XmlParserBuilder())
  .addRecord(Test.class);

Which produces this unformatted/unindented output:

<?xml version="1.0" encoding="utf-8"?><test><field1>ABC</field1></test>

To have the xml formatted (pretty print)/indented use:

StreamBuilder builder = new StreamBuilder("builder_name")
  .format("xml")
  .xmlType(XmlType.NONE)
  .parser(new XmlParserBuilder()
    .indent()
  )
  .addRecord(Test.class);

Note the change to the XmlParserBuilder, to produce this output:

<?xml version="1.0" encoding="utf-8"?>
<test>
  <field1>ABC</field1>
</test>
nicoschl
  • 2,346
  • 1
  • 17
  • 17