我使用 jackson 库得到一行 xml 文件是否正常?

Is it normal that I get one line xml file using jackson library?

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();
}

我希望class人被格式化,但在目标文件中我只有很长的一行:

<?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-->

有什么办法可以解决这个问题吗?

您可以尝试在 XmlMapper 上设置缩进输出功能:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

像这样:

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;
        }
    }
}

输出:

<Person>
  <name>Steven</name>
</Person>