0
public static void main(String[] args) throws Exception {
        Set<Person> personHashSet = new HashSet<>();
        File file = new File(System.getenv("XML_PERSON_FILE_NAME"));
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        XMLStreamWriter sw = xmlOutputFactory.createXMLStreamWriter(new FileOutputStream(file));
        XmlMapper mapper = new XmlMapper();
        sw.writeStartDocument();
        People people = new People();
        people.setPerson(personHashSet);
        mapper.writeValue(sw, people);
        sw.writeComment("Some insightful commentary here");
        sw.writeEndDocument();
}

I expect the class People to be written formatted, but in the target file I only get one very long line:

<?xml version='1.0' encoding='UTF-8'?><people><person><id>3</id><name>Vasiliy</name><coordinates><x>1</x><y>2.0</y></coordinates><xmlCreationDate>1609534800000</xmlCreationDate><height>10.0</height><birthday/><hairColor/><nationality/><location/></person><person><id>1</id><name>Oleg</name><coordinates><x>1</x><y>2.0</y></coordinates><xmlCreationDate>1609534800000</xmlCreationDate><height>10.0</height><birthday/><hairColor/><nationality/><location/></person><person><id>2</id><name>Aleksey</name><coordinates><x>1</x><y>2.0</y></coordinates><xmlCreationDate>1609534800000</xmlCreationDate><height>10.0</height><birthday/><hairColor/><nationality/><location/></person></people><!--Some insightful commentary here-->

Is there any possible ways to fix this?

Alxa
  • 79
  • 1
  • 2
  • 11
  • 2
    Yes this is the default behavior since it consumes less space on the disk and is still desirableness. @DarkMatter's answer should make the output "pretty" and in the more human readable format – joshmeranda Jan 02 '21 at 19:09
  • What format do you mean? May be xhtml? – Roman C Jan 02 '21 at 19:47

1 Answers1

3

You can try setting the indent output feature on the XmlMapper:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

Like this:

public class Main {
    public static void main(String[] args) throws Exception {
        XmlMapper mapper = new XmlMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.writeValue(System.out, new Person("Steven"));
    }
    
    public static class Person {
        final public String name;

        public Person(String name) {
            this.name = name;
        }
    }
}

Output:

<Person>
  <name>Steven</name>
</Person>
DarkMatter
  • 1,007
  • 7
  • 13