2017-07-31 68 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