How to use namespaces in JAXB using EclipseLink MOXy?

I have an XML like:

<message  xmlns:gtm="http:// www.example.com/working/gtm">
    <gtm:header>
    <someid></someid>
    <sometext></sometext>
    </gtm:header>
    <gtm:customer>0123456789</gtm:customer>
</message>

I use mappings @XmlPath. but when I run the code, I get this error:

Exception [EclipseLink-25016] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A namespace for the prefix gtm:header was not found in the namespace resolver.

I wonder what I'm missing?

+3
source share
1 answer

Below is an example of how you can match your use case with EclipseLink JAXB (MOXy) .

package info

First you need to configure namespace information using package level annotation @XmlSchema. We will use the namespace prefixes specified in the annotation @XmlNslater with the annotation @XmlPath.

@XmlSchema(
    namespace="http:// www.example.com/working/gtm",
    xmlns={
        @XmlNs(prefix="gtm", namespaceURI="http:// www.example.com/working/gtm")
    },
    elementFormDefault=XmlNsForm.UNQUALIFIED)
package forum10548370;

import javax.xml.bind.annotation.*; 

Message

@XmlPath XPath MOXy. @XmlSchema elementFormDefault=XmlNsForm.UNQUALIFIED, XPath .

package forum10548370;

import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="message", namespace="")
@XmlAccessorType(XmlAccessType.FIELD)
public class Message {

    @XmlPath("gtm:header/someid/text()")
    private String id;

    @XmlPath("gtm:header/sometext/text()")
    private String text;

    @XmlElement(namespace="http:// www.example.com/working/gtm")
    private String customer;

}

jaxb.properties

MOXy JAXB, jaxb.properties , , (. http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Demo

package forum10548370;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Message.class);

        File xml = new File("src/forum10548370/input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Message message = (Message) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(message, System.out);
    }

}

Input.xml/

<?xml version="1.0" encoding="UTF-8"?>
<message xmlns:gtm="http:// www.example.com/working/gtm">
   <gtm:header>
      <someid></someid>
      <sometext></sometext>
   </gtm:header>
   <gtm:customer>0123456789</gtm:customer>
</message>

+5

All Articles