且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-03 02:22:58

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

Below is some demo code that will produce the XML you are looking for. You can use the Marshaller.JAXB_SCHEMA_LOCATION property to specify the schemaLocation this will cause the http://www.w3.org/2001/XMLSchema-instance namespace to be automatically declared.

演示

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

}

输出

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

Below is the output from running the demo code.

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

package-info

这是你问题中的 package-info 类。

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

import javax.xml.bind.annotation.*;

RootElement

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

Below is a simplified version of your domain model:

package myproject.myapp;

import javax.xml.bind.annotation.XmlRootElement;

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

}