JAXB编组省略前缀

时间:2014-06-13 18:35:44

标签: xml spring jaxb

我有一个JAXB配置,用于将Java对象编组为XML。它完成了这项工作,但是,它省略了名称空间前缀并在编组字符串的前面追加<?xml version="1.0" encoding="UTF-8" standalone="yes"?

    <beans:bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"  p:contextPath="org.ncpdp.schema.script">
         <beans:property name="schema" value="classpath:/schema/SCRIPT_XML_10_6_OPPR.xsd"/>
         <beans:property name="marshallerProperties">
            <beans:map>
                <beans:entry key="jaxb.formatted.output"><beans:value type="boolean">true</beans:value></beans:entry>
                 <beans:entry key="com.sun.xml.internal.bind.namespacePrefixMapper" value-ref="namespaceMapper"></beans:entry>

            </beans:map>
         </beans:proper

ty>
    </beans:bean>

</beans:bean>

public class NamespaceMapper extends NamespacePrefixMapper implements ListenerConstants{

    @Override
    public String getPreferredPrefix(String namespaceUri, String suggestion,
            boolean requirePrefix) {
         if(NAME_SPACE_SCHEMA_URL.equals(namespaceUri)) {
                return NS_PREFIX_SCR;
            } else if(KPRX_NAME_SPACE_URL.equals(namespaceUri)) {
                return NS_PREFIX_V5;
            }
            return suggestion;
    }

}

 public String marshal(final Object object) throws JAXBException {
        final StringWriter writer = new StringWriter();
        final JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class );
        final Marshaller unmarshaller = jaxbContext.createMarshaller();
        unmarshaller.marshal(object, new StreamResult(writer));

        return writer.toString();
    }

我想要一个带有类似

前缀的邮件
<NS2:TEST>
<NS2:ID>123</NS2:ID>
</NS2:TEST>

且没有此声明<?xml version="1.0" encoding="UTF-8" standalone="yes"?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用以下内容修改标题:

unmarshaller.setProperty("com.sun.xml.bind.xmlHeaders", "");
unmarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

命名空间映射可能不会发生,因为您没有告诉您的编组人员您的新实现。

在编组之前,将名称空间前缀属性设置为新的类对象。

unmarshaller.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new NamespaceMapper());

您可能必须删除final修饰符才能修改对象,但我不是100%

顺便说一下,你打电话给你的编组unmarshaller有点困惑,但这是你的代码......