2013-02-05 22 views
-1

我在寫一個將在WebSphere上運行的Java webservice客戶端。我在RAD Developer中創建了一個新的「Web Service Client」項目,爲其提供了我的WSDL,並指定了「自頂向下Java Bean」,並自動生成了一堆文件。Java-WS:對於一個參數是否可以使用原始XML,其餘的仍然使用JAXB對象?

其中一個操作是「GetAddressData」。 RAD Developer自動生成的「GetAddressData.java」和「GetAddressDataResonse.java」,都用「XmlRootElement」註釋。

「GetAddressData」中的一個參數是「RequestData」,一個由四個字符串組成的簡單對象:worfklow,模塊,用戶名和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 "". 

任何幫助深表感謝!先謝謝你。

回答

3

你需要做2件事。

  1. xmlns in your root:<requestOptions xmlns=\"http://www.company.com/ns\">。這可以回溯到您的XSD。
  2. 因爲它聽起來就像是的RequestData不是@XmlRootElement你將不得不解組包裹它在一個JAXBElement的

這裏進行說明:

[email protected][id=fake id, coName=My Co Name, 
    [email protected][type=EXTERNAL, value=me], count=100, 
    requestor=My App Requesting] 

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插件輸出

+1

真棒,它的作品!但是你在哪裏定義了JAXB-bean的命名空間?必須位於bean本身中,因爲當我使用手動創建的DivisionRequestHandler運行示例時,這些字段爲空值。我從XML中刪除xmlns,並且它可以工作。 – surlac

相關問題