开发者

Java xml binding with wrong xmlns attribute name

开发者 https://www.devze.com 2022-12-30 20:17 出处:网络
When I use the annotation: @XmlRootElement(name=\"RootElement\", namespace=\"namespace\") class RootElement {

When I use the annotation:

@XmlRootElement(name="RootElement", namespace="namespace")
class RootElement {

to create xml file from java, it creates the root element as:

<ns2:RootElement xmlns:ns2="namespace">

but I wanted to create without the "ns2", like:

<RootElement xmlns="namespace">

Any idea how to fix it?

Reletad link (example I used to create the开发者_运维问答 xml): http://www.java2s.com/Code/JavaAPI/javax.xml.bind.annotation/XmlRootElementname.htm


JAXB doesn't use xmlns = "namespace" in your case because xmlns = "namespace" also specifies namespace for the child elements, then your first and last elements are in default namespace (because @XmlRootElement doesn't specify namespace for the child elements). So, you need to set namespace for first and last using @XmlElement:

  @XmlElement(namespace = "namespace")
  public String getFirst() {
    return first;
  }

  ...

  @XmlElement(namespace = "namespace")
  public String getLast() {
    return last;
  }

You can also avoid the need to write namespace for every element by using package-level annotation in package-info.java:

@javax.xml.bind.annotation.XmlSchema(
    namespace = "namespace",
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package foo;
0

精彩评论

暂无评论...
验证码 换一张
取 消