使用 jaxb 将命名空间添加到 xml 的根元素 [英] Adding namespaces to root element of xml using jaxb

查看:115
本文介绍了使用 jaxb 将命名空间添加到 xml 的根元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating an xml file whose root elemenet structure shuould be like:

   <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.java 类,但通过编写此代码我只能获得一个命名空间:

i created package-info.java class but i can get only one namespace by writing this code:

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

有什么想法吗?

推荐答案

下面是一些演示代码,可以生成您正在寻找的 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 类.

This is the package-info class from your question.

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

import javax.xml.bind.annotation.*;

根元素

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

Below is a simplified version of your domain model:

package myproject.myapp;

import javax.xml.bind.annotation.XmlRootElement;

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

}

这篇关于使用 jaxb 将命名空间添加到 xml 的根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆