JDOM2- 不要自动关闭标签

问题描述

我正在使用 JDOM 生成一个 XML 文件。由于我没有在元素中放入任何内容,它会自动关闭。这不是我想要的行为,因为用户应该填充文件。是否可以使元素不自动关闭

正在生成文件

 public void generateMigrationFile(String fileName) throws IOException {
        Document migrationDocument=new Document();

        Namespace namespace = Namespace.getNamespace("http://www.liquibase.org/xml/ns/dbchangelog");
        Element databaseChangelogElement = new Element("databaseChangeLog",namespace);
        Namespace XSI = Namespace.getNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");
        databaseChangelogElement.addNamespaceDeclaration(XSI);
        databaseChangelogElement.setAttribute("schemaLocation","http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd",XSI);

        Element changeSetElement=new Element("changeSet",namespace);
        changeSetElement.setAttribute("author","");
        changeSetElement.setAttribute("id",UUID.randomUUID().toString());
        databaseChangelogElement.addContent(changeSetElement);

        migrationDocument.setRootElement(databaseChangelogElement);

        XMLOutputter outter=new XMLOutputter();
        outter.setFormat(Format.getPrettyFormat());
        outter.output(migrationDocument,new FileWriter(new File("migration_files\\"+fileName+".xml")));
        //outter.output(migrationDocument,new FileWriter(new File("C:\\Users\\fabio\\Desktop\\Migrations\\migration_files\\"+fileName+".xml")));

        System.out.println("Migration file generated successfully");
    }

生成文件

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
  <changeSet author="" id="5d4dbc70-39f4-4079-9fc0-7cac291f1c04" />
</databaseChangeLog>

预期生成文件

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
  <changeSet author="" id="5d4dbc70-39f4-4079-9fc0-7cac291f1c04">
  </changeSet> 
</databaseChangeLog>

解决方法

尝试以下解决方案。

使用 Format 对象获取空元素的结束标记。

Format format = Format.getPrettyFormat();
format.setExpandEmptyElements(true);
XMLOutputter outter = new XMLOutputter(format);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...