2017-07-31 93 views
1

我需要使用rest模板發送請求。在發送之前,我需要在發送請求時將對象編組爲xml。我從請求中獲得了響應,但採用了XML格式。然後,我需要將響應xml轉換爲對象,以便將結果顯示在界面上。如何使用jaxb解組xml字符串到java對象

下面是我的控制器,其中i發送請求

@RequestMapping("/searchSummon") 
public String Search(Model model) 
{ 

    model.addAttribute("jaxbExample", new JAXBExample()); 
    model.addAttribute("pdxiRes", new PDXIRes()); 

    JAXBExample jaxbExample = new JAXBExample(); 
    String create_xml = jaxbExample.CreateXML(); 

    System.out.println(create_xml); 

    RestTemplate restTemplate = new RestTemplate(); 
    String a = restTemplate.postForObject("http://192.168.80.30/summon- 
    V2/example", "<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE PDXIReq 
    SYSTEM 'summon.dtd'>" + create_xml,String.class); 

    System.out.println(a); 

    return "searchSummon"; 
} 

我怎麼能解組 'a' 到對象? 類響應 PDXIRes 頭 請求 詳細 狀態

XML的響應( 'A')

<?xml version="1.0" encoding="utf-8"?> 
<PDXIRes> 
<header> 
    <sp_code>abc017637m</sp_code> 
</header> 
<request id="1sq1216272728732"> 
    <id_no>683642435</id_no> 
    <name>SALLY</name> 
    <max_index>1024</max_index> 
    <total_summons>2</total_summons> 
    <summons_detail> 
     <row num="1"> 
      <summons_id>1810000200002AQ639332</summons_id> 
      <vehicle>NN162</vehicle> 

     </row> 
     <row num="2"> 
      <summons_id>1810000200002AM947772</summons_id> 
      <vehicle>NN162</vehicle 
     </row> 
    </summons_detail> 
    <status> 
     <status_code>01</status_code> 
     <status_msg>Successful</status_msg> 
    </status> 
    </request> 
    </PDXIRes> 
+0

如果你想使用REST框架類似新澤西編組/解組過程是自動處理... –

+0

請檢查https://stackoverflow.com/questions/25704853/ unmarshalling-nested-list-of-xml-items-using-jaxb幫助... – deepakl

回答

0

你可以做,使用Unmarshaller的。

JAXBContext jaxbContext = JAXBContext.newInstance(Person.class); 
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 

StringReader reader = new StringReader("xml string here"); 
Person person = (Person) unmarshaller.unmarshal(reader); 

這裏找到:Use JAXB to create Object from XML String