使用jaxb将名称空间添加到xml的根元素

Aqu*_*s24 21 xsd jaxb xml-namespaces

我正在创建一个xml文件,其根元素结构应该是这样的:

   <RootElement xmlns="http://www.mysite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mysite.com/abc.xsd">
Run Code Online (Sandbox Code Playgroud)

我创建了package-info.java类,但是通过编写这段代码我只能获得一个命名空间:

@XmlSchema(
        namespace = "http://www.mysite.com",
        elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package myproject.myapp;
import javax.xml.bind.annotation.XmlSchema;
Run Code Online (Sandbox Code Playgroud)

任何的想法?

bdo*_*han 30

下面是一些演示代码,它将生成您正在寻找的XML.您可以使用该Marshaller.JAXB_SCHEMA_LOCATION属性指定schemaLocation这将导致http://www.w3.org/2001/XMLSchema-instance自动声明命名空间.

演示

package myproject.myapp;

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(RootElement.class);

        RootElement rootElement = new RootElement();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.mysite.com/abc.xsd");
        marshaller.marshal(rootElement, System.out);
    }

}
Run Code Online (Sandbox Code Playgroud)

产量

以下是运行演示代码的输出.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RootElement xmlns="http://www.mysite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mysite.com/abc.xsd"/>
Run Code Online (Sandbox Code Playgroud)

包信息

这是package-info你问题的课程.

@XmlSchema(
    namespace = "http://www.mysite.com",
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED
)
package myproject.myapp;

import javax.xml.bind.annotation.*;
Run Code Online (Sandbox Code Playgroud)

rootElement的

以下是您的域模型的简化版本:

package myproject.myapp;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="RootElement")
public class RootElement {

}
Run Code Online (Sandbox Code Playgroud)