JAXB namespace prefixes missing

2019-01-17 00:34发布

I have generated Java classes from XSD, all works fine from a unmarshalling point of view.

However, when I marshall from JAXB classes I get the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<message xmlns="http://poc.cmc.com/ScreenLayout">
    <Data>
        <Type>Sample</Type>
     . . .
</message>

But I need

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns0:message xmlns:ns0="http://poc.cmc.com/ScreenLayout">
    <ns0:Data>
        <ns0:Type>Sample</ns0:Type>
    . . .

how can I control that from Java?

Thanks a lot

标签: java jaxb
3条回答
Lonely孤独者°
2楼-- · 2019-01-17 01:05

Cant post this as a comment!

because the consuming application is very dumb and needs the prefix

In that case the dumb application is not really consuming xml. Take a look at this link http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html and play with the namespace options. Specifically

@XmlSchema (
   xmlns = {
         @javax.xml.bind.annotation.XmlNs(prefix = "ns1", namespaceURI="http:test"),
         @javax.xml.bind.annotation.XmlNs(prefix = "xsd", namespaceURI="http:www.w3.org2001XMLSchema")
   },
   namespace = "http:test",
   elementFormDefault = XmlNsForm.UNQUALIFIED,
   attributeFormDefault = XmlNsForm.UNSET
)

used in a package-info.java file.

@XmlType(namespace="http://www.example.org/type")

Used on a class declaration

@XmlElement(namespace="http://www.example.org/property")

Used on a property.

Some combination or only one of these options may give you what you want. However you should understand that you're fighting an uphill battle when you move from valid xml to xml that must contain a specific namespace prefix on all elements.

查看更多
家丑人穷心不美
3楼-- · 2019-01-17 01:14

You can use the @XmlSchema annotation on a package-info class to assign a prefix to the namespace:

@XmlSchema(
    namespace = "http://poc.cmc.com/ScreenLayout",
    elementFormDefault = XmlNsForm.QUALIFIED,
    xmlns={@XmlNs(prefix="ns0", namespaceURI="http://poc.cmc.com/ScreenLayout")})    
package your.package;


import javax.xml.bind.annotation.*;
查看更多
一纸荒年 Trace。
4楼-- · 2019-01-17 01:17

According to XML spec both xml's are the same, as xmlns="" defines default namespace which applies to current and all child elements. XML parsers should give you the same DOM or SAX in both cases

查看更多
登录 后发表回答