javaxmljdom-2

JDOM2- Don't auto close tags


I am generating a XML file using JDOM . Since I didn't put any content in a element , it auto closes . This is not the behavior I want , because the user is supposed to fill the file. Is it possible to make the element not auto close itself?

Generating file

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

Generated file

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

Expected generated file

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

Solution

  • try with following solution.

    use the Format object to get closing tag for empty element.

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