JAXB将命名空间赋予非根元素

时间:2016-05-30 05:39:01

标签: java xml xsd jaxb saml

要求是这样的

<samlp:Response xmlns:samlp="something1" >
    <saml:EncryptedAssertion xmlns:saml="something2">
         <EncryptedData xmlns="something3" >
             some more tags with namespace
         </EncryptedData> 
    </saml:EncryptedAssertion>
</samlp:Response>

我使用package-info.java获得了根级别的前缀和命名空间,但我无法在非根级别获取命名空间,即

这是我能够实现的目标

<samlp:Response xmlns:samlp="something1" xmlns:saml="something2" xmlns:ns6="someting3">
    <saml:EncryptedAssertion >
        <EncryptedData >
            some more tags with namespace
        </EncryptedData>
    </saml:EncryptedAssertion>
</samlp:Response>

package-info.java

@XmlSchema(
        namespace="something1",

    elementFormDefault=XmlNsForm.UNQUALIFIED,
    attributeFormDefault =XmlNsForm.UNQUALIFIED,
    xmlns={ 
            @XmlNs(prefix = "samlp", namespaceURI = "somthing1"),
            @XmlNs(prefix = "saml", namespaceURI = "something2"),
            @XmlNs(prefix = "", namespaceURI = "something3"),
    }
)

我知道命名空间可以在父节点或根节点中定义,它会有效,但是我正在使用Web服务,因此我不确定在父级别声明的名称空间是否会在解组时产生任何差异这就是为什么我试图产生精确的saml响应。

1 个答案:

答案 0 :(得分:0)

This is how I did it. Not sure weather its right or wrong, but it worked for the scenario which i mentioned in question.

  1. Added required attribute in particular JAXBclass

    public class EncryptedAssertionType {
    @XmlAttribute(name = "xmlns:saml")
    protected String samlNamespace;
    
  2. Generated getters/setters for same variable and set the variable while marshalling

    EncryptedAssertionType encryptedAssertion = new EncryptedAssertionType();
    encryptedAssertion.setSamlNamespace("something2");
    

    You can add such attribute to all levels if you need

No need to include package-info.java

This gave me expected response

    <samlp:Response xmlns:samlp="something1" >
    <saml:EncryptedAssertion xmlns:saml="something2">