使用 JDOM 添加命名空间

问题描述

我正在尝试生成一个 XML 文件,但我遇到了严重的问题。如果我使用方法 addNamespaceDeclaration,我会收到以下错误

xception in thread "main" org.jdom2.IllegalNameException: The name "http://www.liquibase.org/xml/ns/dbchangelog" is not legal for JDOM/XML Namespace prefixs: The prefix xmlns (any case) can only be bound to only the 'http://www.w3.org/2000/xmlns/' uri..
    at org.jdom2.Namespace.getNamespace(Namespace.java:232)
    at com.migrations.demo.MigrationGenerator.generateMigrationFile(MigrationGenerator.java:24)
    at com.migrations.demo.MigrationsApplication.main(MigrationsApplication.java:15)

我也尝试使用 setNamespace 但即使它添加了命名空间,这个也被添加到子元素中(我将在下面留下输出)。如何添加命名空间?

XML 预期文件

<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="randomId">
    </changeSet>
</databaseChangeLog>

使用 setNamespace 生成的 XML

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog">
  <changeSet xmlns="" author="" id="randomId">Insert action here</changeSet>
</databaseChangeLog>

生成方法

public void generateMigrationFile() throws IOException {

        //MUST ADD ATTRIBUTES TO THE ELEMENTS

        Document migrationDocument=new Document();
        Namespace ns = Namespace.getNamespace("http://www.liquibase.org/xml/ns/dbchangelog");
        //Namespace ns2 = Namespace.getNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");
        //Namespace ns3 = Namespace.getNamespace("ns3","http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd");

        //elements the xml file will contain
        Element databaseChangelogElement=new Element("databaseChangeLog");

        databaseChangelogElement.setNamespace(ns);

        Element changeSetElement=new Element("changeSet");
        changeSetElement.setAttribute("author","");
        changeSetElement.setAttribute("id","randomId");
        changeSetElement.addContent("Insert action here");
        databaseChangelogElement.addContent(changeSetElement);

//Define root element like root
        migrationDocument.setRootElement(databaseChangelogElement);

//Create the XML
        XMLOutputter outter=new XMLOutputter();
        outter.setFormat(Format.getPrettyFormat());
        outter.output(migrationDocument,new FileWriter(new File("testFile.xml")));

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

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