如何将实体对象转换为XML

时间:2016-06-21 11:14:16

标签: rest resteasy

我有一个包含大量实体(javax.persistence.Entity)对象的遗留系统。这些实体中的每一个都与其他实体具有一对多的关系。

我的要求是通过REST API公开这些实体。我打算使用resteasy(目前的产品在jboss-7上运行)。我的问题是,设计这个的最佳方法是什么?

最初,我曾想过使用JAXB带注释的DTO对象并使用getter / setter转换所有实体。还有其他选择吗?

1 个答案:

答案 0 :(得分:0)

Create One class like this

    public class Employee
    {
         public int employee_code {set; get; } 
         public string first_name {set; get; } 
         public string middle_name {set; get; }
         public string last_name {set; get; }
         public string designation {set; get; }
         public string department {set; get; }
         public string present_address {set; get; }
         public string permament_address {set; get; }
         public DateTime DOB {set; get; }
         public Double Gross_Salary {set; get; }
    } 

now create a method for xml creation using this namespace
    using System.Xml.Serialization;

public string CreateXML(Object YourClassObject){    
      XmlDocument xmlDoc =new XmlDocument();   //Represents an XML document, 
                // Initializes a new instance of the XmlDocument class.          
      XmlSerializer xmlSerializer = new             XmlSerializer(YourClassObject.GetType());            
    // Creates a stream whose backing store is memory. 
       using (MemoryStream xmlStream =new MemoryStream())
       { 
        xmlSerializer.Serialize(xmlStream, YourClassObject);
        xmlStream.Position = 0;
        //Loads the XML document from the specified string.
        xmlDoc.Load(xmlStream); 
        return xmlDoc.InnerXml;
       }
}

now call this method
string strView =CreateXML(YourClassObject);