问题描述
我正在创建一个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类但是通过编写这段代码我只能获得一个命名空间: / p>
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
这是你问题中的 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 {
}
这篇关于使用jaxb将名称空间添加到xml的根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!