问题
I'm having trouble adding namespace to property for some time now. My requirement is to create xml which will have namespace uri on child element rather than root. I'm using jaxb with eclipselink moxy, jdk7.
<document>
<Date> date </Date>
</Type>type </Type>
<customFields xmlns:pns="http://abc.com/test.xsd">
<id>..</id>
<contact>..</contact>
</customFields>
</document>
Classes are:
@XmlRootElement(name = "document")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"type","date", "customFields"})
public class AssetBean {
@XmlElement(name="Type")
private String type;
@XmlElement(name="Date")
@XmlElement(name = "CustomFields",namespace = "http://api.source.com/xsds/path/to/partner.xsd")
private CustomBean customFields = new CustomBean();
//getters/setters here
}
public class CustomBean {
private String id;
private String contact;
//getter/setter
}
package-info.java
@javax.xml.bind.annotation.XmlSchema (
xmlns = {
@javax.xml.bind.annotation.XmlNs(prefix="pns",
namespaceURI="http://api.source.com/xsds/path/to/partner.xsd")
},
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED
)
package com.abc.xyz
I followed this article for help but cant get what I'm trying http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
Thank you
回答1:
Domain Model (Root)
In the domain object below I'll assign a namespace to one of the elements using the @XmlElement
annotation.
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
String foo;
@XmlElement(namespace="http://www.example.com")
String bar;
}
Demo Code
In the demo code below we will create an instance of the domain object and marshal it to XML.
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Root root = new Root();
root.foo = "FOO";
root.bar = "BAR";
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Output
Below is the output of running the demo code. The element that we assigned the namespace to with the @XmlElement
annotation is properly namespace qualified, but the namespace declaration appears on the root element.
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:ns0="http://www.example.com">
<foo>FOO</foo>
<ns0:bar>BAR</ns0:bar>
</root>
For More Information
- http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
来源:https://stackoverflow.com/questions/16438692/jaxb-xmlelement-namespace-not-working