使用jaxb向xml的根元素添加名称空间
我正在创建一个xml文件,其根elemenet结构如下:使用jaxb向xml的根元素添加名称空间,jaxb,xsd,xml-namespaces,Jaxb,Xsd,Xml Namespaces,我正在创建一个xml文件,其根elemenet结构如下: <RootElement xmlns="http://www.mysite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mysite.com/abc.xsd"> 有什么想法吗?下面是一些演示代码,可以生成您正在寻找的XML。您可以使用Marshaller.JAXB_SCHEMA_LOC
<RootElement xmlns="http://www.mysite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mysite.com/abc.xsd">
有什么想法吗?下面是一些演示代码,可以生成您正在寻找的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);
}
}
输出
下面是运行演示代码的输出
<?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"/>
RootElement
以下是域模型的简化版本:
package myproject.myapp;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="RootElement")
public class RootElement {
}
在较旧的Jaxb中,您可以使用
@xmlseea
指定其他名称空间,而在较新的Jaxb中,您可以在package-info.java中使用@XmlNs
,请参见以下答案:schemaLocation应该是“{namespace}{schema uri}”
:xsi:schemaLocation=”http://www.example.com http://www.example.com/abc.xsd“
@XmlSchema(
namespace = "http://www.mysite.com",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED
)
package myproject.myapp;
import javax.xml.bind.annotation.*;
package myproject.myapp;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="RootElement")
public class RootElement {
}