2017-01-05 3 views
-1

Я хочу преобразовать сложный объект в XML-данные только с одним корневым узлом.Нужно преобразовать сложный объект в Xml в .Net C#

public class Customer 
{ 
    public Address Address { get; set; } 
    public User user { get; set; } 
} 

public class Address 
{ 
    public string city { get; set; } 
    public string State { get; set; } 
} 

public class User 
{ 
    public string Name { get; set; } 
    public string Id { get; set; } 
    public Dictionary<String, String> response { get; set; } 
} 

У меня есть класс клиентов, которые содержат Address и User свойства. Я хочу преобразовать объект Customer в XML-данные с одним корневым узлом.

Я хочу, чтобы объект в формате XML ниже

<row> 
    <cell cellType="city">Chennai</cell> 
    <cell cellType="state">tamilnadu</cell> 
    <cell cellType="name">test</cell> 
    <cell cellType="id">001</cell> 
    <cell cellType="response1">response1</cell> 
    <cell cellType="response2">response2</cell> 
</row> 
+0

Не рассказанной почему вы используете атрибуты для имени значения? Почему не ' Chennai tamilnadu ...' и так далее? – Fabio

+1

Возможный дубликат [Сериализация объекта в XML] (http://stackoverflow.com/questions/4123590/serialize-an-object-to-xml) –

ответ

0

Try XML LINQ:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication34 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Customer customer = new Customer() 
      { 
       Address = new Address() 
       { 
        city = "Chennai", 
        State = "tamilnadu", 
       }, 
       user = new User() 
       { 
        Name = "test", 
        Id = "001", 
        response = new Dictionary<string, string>() { 
         { "response1", "response1"}, 
         { "response2", "response2"} 
        } 
       } 
      }; 

      XElement row = new XElement("row", new object[] { 
       new XElement("cell", new object[] { 
        new XAttribute("cellType", "city"), 
        customer.Address.city 
       }), 
       new XElement("cell", new object[] { 
         new XAttribute("cellType", "state"), 
         customer.Address.State 
        }), 
       new XElement("cell", new object[] { 
         new XAttribute("cellType", "name"), 
         customer.user.Name 
        }), 
       new XElement("cell", new object[] { 
         new XAttribute("cellType", "id"), 
         customer.user.Id 
        }), 
        customer.user.response.AsEnumerable().Select(x => new XElement("cell", new object[] { 
         new XAttribute("cellType",x.Key), 
         x.Value 
        })) 
      }); 

     } 

     //<row> 
     // <cell cellType="city">Chennai</cell> 
     // <cell cellType="state">tamilnadu</cell> 
     // <cell cellType="name">test</cell> 
     // <cell cellType="id">001</cell> 
     // <cell cellType="response1">response1</cell> 
     // <cell cellType="response2">response2</cell> 
     //</row> 
    } 
    public class Customer 
    { 
     public Address Address { get; set; } 
     public User user { get; set; } 
    } 

    public class Address 
    { 
     public string city { get; set; } 
     public string State { get; set; } 
    } 

    public class User 
    { 
     public string Name { get; set; } 
     public string Id { get; set; } 
     public Dictionary<String, String> response { get; set; } 
    } 

} 
0

Вы не можете сделать это с основной XML-сериализации в C#, но вы можете создать DTO класс для достижения своей цели. Используйте DTO как это и сопоставить объекты к нему:

[XmlRoot("row")] 
public class RowDto 
{ 
    [XmlElement("cell")] 
    public List<Cell> Cells { get; set; } 
} 

public class Cell 
{ 
    [XmlAttribute("cellType")] 
    public string Type { get; set; } 

    [XmlText] 
    public string Value { get; set; } 
} 
+0

В моем объекте также содержится словарь. Итак, как преобразовать его в xml с одним корневым узлом – Arun

+0

Это зависит от того, что является ключом в вашем словаре ответов –

Смежные вопросы