如何拥有自定义命名空间前缀 [英] How to have custom namespace prefix
问题描述
我是JAXB的新手。我能够填充XML。在我的情况下,我需要我的命名空间前缀为
I am new to JAXB. I am able to populate the XML. In my case I need my namespace prefix as
<set xmlns="www.google.com"
xmlns:myName="www.google.com">
而不是
<set xmlns="www.google.com"
xmlns:ns2="www.google.com">
我使用了 package-info
类和还有 @XmlType
注释。我是否需要添加任何变量来获取第二个命名空间的所需名称,如xmlns:MyName而不是xmlns:ns2?
I have used package-info
class and also the @XmlType
annotation. Do I need to add any variable to get the desired name for the second namespace like "xmlns:MyName' instead of "xmlns:ns2"?
推荐答案
如果您使用的是 EclipseLink JAXB(MOXy) 作为您的JAXB提供商或最新版本的JAXB RI,您可以执行以下操作:
If you are using EclipseLink JAXB (MOXy) as your JAXB provider or a recent version of the JAXB RI then you can do the following:
package-info
您可以在 xmlns
属性中使用 @XmlNs
注释 @XmlSchema
注释,用于指定命名空间的前缀。
You can use the @XmlNs
annotation on the xmlns
property of the @XmlSchema
annotation to specify the prefix for a namespace.
@XmlSchema(
namespace="www.google.com",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns={
@XmlNs(namespaceURI = "www.google.com", prefix = ""),
@XmlNs(namespaceURI = "www.google.com", prefix = "myName"),
})
package forum13817126;
import javax.xml.bind.annotation.*;
Java模型
下面是一个简单的Java模型,我将在本例中使用。
Below is a simple Java model that I will use for this example.
package forum13817126;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Set {
}
演示代码
以下演示代码将创建域模型的实例并将其编组为XML。
The following demo code will create an instance of the domain model and marshal it to XML.
package forum13817126;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Set.class);
Set set = new Set();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(set, System.out);
}
}
输出
以下是运行演示代码的输出。
Below is the output from running the demo code.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myName:set xmlns="www.google.com" xmlns:myName="www.google.com"/>
更多信息
- http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
这篇关于如何拥有自定义命名空间前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!