user1833083
user1833083

Reputation: 21

How to make following class objects to xml?

I have following class. (SIMModel, Product, Item)

public class SIMModel
{
    public Product Product { get; set; }
}

public class Product
{
    public List<Item> Items { get; set; }
}

public class Item
{
    [XmlAttribute("ID")]
    public String ID { get; set; }
    [XmlAttribute("Name")]
    public String Name { get; set; }

    public Child_Item Child_Item { get; set; }
    public Parent_Item Parent_Item { get; set; }
}

public class Child_Item
{
    [XmlAttribute("ID")]
    public String ID { get; set; }
}

And I want to make this XML

 <SIMModel>
  <Product>
   <Item ID="N" Name="N-1">
    <Child_Item ID="N-1-1">
   </Item>
  </Proudct>
 </SIMModel>

How can i make the Simulation XML using upper class? I don't know how to wrap each class..

Upvotes: 2

Views: 70

Answers (1)

Petrutiu Mihai
Petrutiu Mihai

Reputation: 575

I made a simple Serialize method that serializes to string and removes the namespaces.

private static void Main(string[] args)
{
    string result = Serialize(new SIMModel
    {
        Product = new Product
        {
            Items = new List<Item>
            {
                new Item
                {
                    ID = "N",
                    Name = "N-1",
                    Child_Item = new Child_Item {ID = "N-1-1"}
                }
            }
        }
    });
    Console.WriteLine(result);
}

public static string Serialize<T>(T value)
{
    if (value == null)
    {
        return null;
    }
    //Create our own namespaces for the output
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

    //Add an empty namespace and empty value
    ns.Add("", "");

    XmlSerializer serializer = new XmlSerializer(typeof (T));

    XmlWriterSettings settings = new XmlWriterSettings
    {
        Encoding = new UnicodeEncoding(false, false),
        Indent = true,
        OmitXmlDeclaration = true
    };

    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            serializer.Serialize(xmlWriter, value, ns);
        }
        return textWriter.ToString();
    }
}

Output:

<SIMModel>
  <Product>
    <Items>
      <Item ID="N" Name="N-1">
        <Child_Item ID="N-1-1" />
      </Item>
    </Items>
  </Product>
</SIMModel>

Upvotes: 1

Related Questions