2013-09-25 40 views
-1

我正在將XML轉換爲對象和對象XML。當我嘗試將我的XML轉換爲嵌套有相同對象但無法實現的對象時,請告訴我如何在春天實現此目標。下面是我的XML,如何將XML轉換爲java中的對象?

<?xml version=\"1.0\" encoding=\"UTF-8\"?> 
<ProductHierarchyDTO> 
    <id>45</id> 
    <szName>LIB-pappu</szName> 
    <szDescription>LIB-pappu</szDescription> 
    <iParentid>30003305</iParentid> 
    <cIsActive>Y</cIsActive> 
    <cIsProduct>N</cIsProduct> 
    <productHierarchyList> 
     <ProductHierarchyDTO> 
      <id>48</id> 
      <szName>LIB-pappu-123</szName> 
      <szDescription>LIB-pappu-123</szDescription> 
      <iParentid>45</iParentid> 
      <cIsActive>Y</cIsActive> 
      <cIsProduct>Y</cIsProduct> 
     </ProductHierarchyDTO> 
     <ProductHierarchyDTO> 
      <id>49</id> 
      <szName>LIB-pappu-321</szName> 
      <szDescription>LIB-pappu-123</szDescription> 
      <iParentid>45</iParentid> 
      <cIsActive>Y</cIsActive> 
      <cIsProduct>Y</cIsProduct> 
     </ProductHierarchyDTO> 
    </productHierarchyList> 
</ProductHierarchyDTO> 

在此先感謝

+1

那你試試這麼遠嗎?代碼請 –

+0

以下將幫助:http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted –

+0

嘗試jaxbContext = JAXBContext.newInstance(ProductHierarchyDTO.class); jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); ProductHierarchyDTO productHierarchyDTO =(ProductHierarchyDTO) \t \t \t \t \t \t jaxbUnmarshaller.unmarshal(新ByteArrayInputStream進行(xml.getBytes())); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); jaxbMarshaller.marshal(productHierarchyDTO,System.out); (例外e){ \t \t} catch(Exception e){ \t \t \t e.printStackTrace(); \t \t} – user2815491

回答

0

隨着JAXB你可以你的類模型是這樣的:

import java.util.List; 
import javax.xml.bind.annotation.*; 

@XmlRootElement(name="ProductHierarchyDTO") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class ProductHierarchyDTO { 

    private int id; 

    @XmlElementWrapper 
    @XmlElementRef 
    private List<ProductHierarchyDTO> productHierarchyList; 

}