Javax.xml.bind.PropertyException when jaxb marshalling

I am trying to arrange a list of objects in xml. The following is the method:

import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
import javax.xml.bind.Marshaller;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

public class ItemMarshaller
{
    public String marshallItems(final List<Items> items)
    {
        try
        {
            final JAXBContext context = JAXBContext.newInstance("com.project.jaxb.items");
            final Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper()
            {
                @Override
                public String getPreferredPrefix(String uri, String suggestion, boolean requirePrefix)
                {
                    return "";
                }
            });

            final StringWriter writer = new StringWriter();
            m.marshal(items, writer);

            return writer.toString();
        }
        catch (final JAXBException e)
        {
            ErrorLogger.LOGGER.error("Marshalling failed.", e); //$NON-NLS-1$
        }

        return null;
    }
}

When I call m.setProperty ("com.sun.xml.bind.namespacePrefixMapper", the new NamespacePrefixMapper (), I get the following error:

javax.xml.bind.PropertyException: name: com.sun.xml.bind.namespacePrefixMapper value: com.project.ItemMarshaller$1@eb6e072
at javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(AbstractMarshallerImpl.java:358)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty(MarshallerImpl.java:527)

Now, if I use the inner class: com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper;

instead it works. However, this project must be built using maven, and it complains when you have dependency on the inner class. Also, it is a bad idea to use inner classes, or so they tell me.

How can i fix this?

+5
source share
1 answer

1. package-info.java NamespacePrefixMapper:

@javax.xml.bind.annotation.XmlSchema(
        namespace = "http://www.example.com/schema/impl", 
        elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
        xmlns={@XmlNs(prefix="ns0", namespaceURI="http://www.example.com/schema/impl")}
    )
package com.abc.schema.impl;

2: Maven :

<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl -->
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2.4-1</version>
</dependency>

com.sun.xml.bind.marshaller.NamespacePrefixMapper.

+2

Source: https://habr.com/ru/post/1676896/


All Articles