JAXB generate XML element with package name

I am trying to generate a simple XML from POJO using JAXB. Here is my XML output:

<Customer>
    <name>abcd</name>
</Customer>

<com.some.pkg.Customer>
    <name>abcd1231</name>
</com.some.pkg.Customer>

This is invalid XML: element names cannot contain dots or spaces, or other punctuation... though - is allowed. So this specific XML cannot be generated, with JAXB or otherwise (as it's not XML).

Instead, the JAXB thing to do is to use annotations on a package-info file which customise how namespacing of the element is handled (namespace prefixes, generating fully qualified names etc.).

That way you would end up with something like:

<ns:Customer xmlns:ns="com.some.pkg">
  <ns:name>abcd1231</ns:name>
</ns:Customer>

Example package-info.java file for com.some.pkg

@XmlSchema(namespace = "com.some.pkg", 
           xmlns = { @XmlNs(namespaceURI = "com.some.pkg", prefix = "ns") },
           attributeFormDefault = XmlNsForm.QUALIFIED, 
           elementFormDefault = XmlNsForm.QUALIFIED)
package com.some.pkg;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
链接地址: http://www.djcxy.com/p/62972.html

上一篇: Haskell的有限域线性代数库

下一篇: JAXB生成包名称的XML元素