我正在编写一个将在 WebSphere 上运行的 Java Web 服务客户端。我在 RAD Developer 中创建了一个新的“Web 服务客户端”项目,给它我的 WSDL,指定了“Top down Java Bean”,它自动生成了一堆文件。
其中一个操作是“GetAddressData”。 RAD Developer 自动生成的“GetAddressData.java”和“GetAddressDataResonse.java”,都带有“XmlRootElement”注释。
“GetAddressData”中的参数之一是“RequestData”,这是一个由四个字符串组成的简单对象:worfklow、module、username 和id。 RAD Developer 也为我生成了一个“RequestData.java”。
问:有什么方法可以用原始 XML 代替 JAXB“RequestData”对象,而不是一次打包和解包记录一个字段?
我试过这样的事情:
private static String theXml =
"<requestOptions>\n" +
" <WorkflowName>unmarshalTestWorkflow</WorkflowName>\n" +
" <ModuleName>unmarshalTestModule</ModuleName>\n" +
" <UserName>unmarshalTestName</UserName>\n" +
" <TransactionId>0099</TransactionId>\n" +
"</requestOptions>\n";
private RequestOptions mkRequestOptions () throws Exception {
JAXBContext context = JAXBContext.newInstance(RequestOptions.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Object obj = unmarshaller.unmarshal(new StringReader (theXml));
RequestOptions requestOptions = (RequestOptions)obj;
...
但我不断得到:
error: Unexpected element "requestOptions". Expected elements are "".
任何帮助将不胜感激!提前谢谢你。
你需要做两件事。
<requestOptions xmlns=\"http://www.company.com/ns\">
。这可以追溯到您的 XSD。这里有插图:
public class Test
{
static String randomXml =
"<divisionRequestHeader xmlns=\"http://www.company.com/ns/\">"
+ "<id>fake id</id>"
+ "<CoName>My Co Name</CoName>" + "<User>"
+ "<Type>EXTERNAL</Type>" + "<Value>me</Value>" + "</User>"
+ "<Count>100</Count>"
+ "<Requestor>My App Requesting</Requestor>"
+ "</divisionRequestHeader>";
public static void main(String[] args) throws Exception
{
JAXBContext context = JAXBContext.newInstance(DivisionRequestHeader.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Source source = new StreamSource(new StringReader(randomXml));
JAXBElement<DivisionRequestHeader> jaxbElement = unmarshaller.unmarshal(source,
DivisionRequestHeader.class);
DivisionRequestHeader header = jaxbElement.getValue();
System.out.println(header.toString());
}
}
使用 jaxb toString 插件输出:
com.company.ns.DivisionRequestHeader@620c620c[id=fake id, coName=My Co Name,
user=com.company.ns.User@79e479e4[type=EXTERNAL, value=me], count=100,
requestor=My App Requesting]