本文介绍了JAXB:需要所有元素的命名空间前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring WebServiceTemplate进行webservice调用,该调用使用JAXB生成请求XML。我的要求需要所有元素(包括root)在SOAP请求中都有一个名称空间前缀(只有一个名称空间)。

I am Using Spring WebServiceTemplate to make webservice call which uses JAXB to generate request XML. My requirement needs all the elements (including root) to have a namespace prefix (there is only a single namespace) in the SOAP request.

Ex:

<ns1:Login xmlns:ns1="www.example.com/a">
    <ns1:username>abc</ns1:username>
    <ns1:password>abc</ns1:password>
</ns1:Login>

但我得到了

<Login xmlns="www.example.com/a">
    <username>abc<username>
    <password>abc<password>
</Login>

xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema targetNamespace="www.example.com/a"   xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ilreq="www.example.com/a" elementFormDefault="qualified" attributeFormDefault="unqualified">

<xs:complexType name="Login">
    <xs:sequence>
        <xs:element name="username" type="xs:string"/>
        <xs:element name="password" type="xs:string"/>
    </xs:sequence>
</xs:complexType>

从XSD生成的Java类

Generated Java Class from XSD

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Login", propOrder = {
    "username",
    "password"
})

@XmlRootElement
public class Login {

@XmlElement(required = true)
protected String username;
@XmlElement(required = true)
protected String password;
......
}

package-info.java

package-info.java

@javax.xml.bind.annotation.XmlSchema(
    namespace = "www.example.com/a",
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package authenticator.beans.login;

想知道如何使用Namespace前缀生成包含root的所有元素的请求XML。

Want to know how to generate the request XML with Namespace prefix to all elements including root.

推荐答案

解决方法:添加

@XmlSchema(
    namespace = "http://www.example.com/a",
    elementFormDefault = XmlNsForm.QUALIFIED,
    xmlns = {
        @XmlNs(prefix="ns1", namespaceURI="http://www.example.com/a")
    }
)

package authenticator.beans.login;
import javax.xml.bind.annotation.*;

in package-info.java

in package-info.java

帮助:答案由Blaise Doughan提供

Took help of jaxb-namespaces-missing : Answer provided by Blaise Doughan

这篇关于JAXB:需要所有元素的命名空间前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:14