2

I have xml like this :

<Root>
 <Products> 
    <Product>
      <ProductCode>1</ProductCode>
      <Properties no="45">
        <ColorProperties>
           <Color>Blue</Color>
        </ColorProperties>
      </Properties>
    </Product>
    <Product>
      <ProductCode>2</ProductCode>
      <Properties no="45">
        <ColorProperties>
           <Color>Red</Color>
        </ColorProperties>
      </Properties>
    </Product>
     <Product>
      <ProductCode>3</ProductCode>
      <Properties no="45">
        <ColorProperties>
           <Color>Yellow</Color>
        </ColorProperties>
      </Properties>
    </Product>
 </Products>
</Root>

And I want to convert to Product Model,

class Product 
{
//must be filled
}

And there must me attributes for top of the Product class that say to Product belongs to Products and Products belong to Root.

How can I make this ?

My english not great sorry for that :) .

So I do not want create Root and Products Classes (there must be multiple [XmlRoot] I think), and I want decorate Properties (and it's nested properties) with [XmlArray] and [XmlArrayItem] but I could not make it.

How can convert this xml to Product class with c# ?

3
  • You can try xmltocsharp.azurewebsites.net to autogenerate classes. Commented Apr 8, 2022 at 10:54
  • 1
    If you're using visual studio, 'Special Paste' ->> XML as class Commented Apr 8, 2022 at 10:54
  • I tried these kind sites and Special Paste' method and they are generating classes for Root and Products but I do not want to create classes for Root and Products. Commented Apr 8, 2022 at 10:58

1 Answer 1

1

You can scaffold any entity to a POCO class by using Visual Studio's special paste magic ( Edit - Special Paste - Paste as XML )

And I exactly did that to generate your entity classes by using your XML file.

Now, Let's say we have the following Entity classes :

using System;
using System.ComponentModel;
using System.Xml.Serialization;

namespace XmlToClass
{

[Serializable()]
[DesignerCategory("code")]
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = false)]
public partial class Root
{

    private RootProduct[] productsField;

    [XmlArrayItem("Product", IsNullable = false)]
    public RootProduct[] Products
    {
        get
        {
            return this.productsField;
        }
        set
        {
            this.productsField = value;
        }
    }
}


[Serializable()]
[DesignerCategory("code")]
[XmlType(AnonymousType = true)]
public partial class RootProduct
{

    private byte productCodeField;

    private RootProductProperties propertiesField;

    public byte ProductCode
    {
        get
        {
            return this.productCodeField;
        }
        set
        {
            this.productCodeField = value;
        }
    }

    public RootProductProperties Properties
    {
        get
        {
            return this.propertiesField;
        }
        set
        {
            this.propertiesField = value;
        }
    }
}

[Serializable()]
[DesignerCategory("code")]
[XmlType(AnonymousType = true)]
public partial class RootProductProperties
{

    private RootProductPropertiesColorProperties colorPropertiesField;

    private byte noField;

    public RootProductPropertiesColorProperties ColorProperties
    {
        get
        {
            return this.colorPropertiesField;
        }
        set
        {
            this.colorPropertiesField = value;
        }
    }

    [XmlAttribute()]
    public byte no
    {
        get
        {
            return this.noField;
        }
        set
        {
            this.noField = value;
        }
    }
}


[Serializable()]
[DesignerCategory("code")]
[XmlType(AnonymousType = true)]
public partial class RootProductPropertiesColorProperties
{

    private string colorField;

    /// <remarks/>
    public string Color
    {
        get
        {
            return this.colorField;
        }
        set
        {
            this.colorField = value;
        }
    }
}

}

Simply add this helper class with a generic method :

    public class XmlToEntity
{
    public T FromXml<T>(String xml)
    {
        T returnedXmlClass = default(T);

        try
        {
            using (TextReader reader = new StringReader(xml))
            {
                try
                {
                    returnedXmlClass =
                        (T)new XmlSerializer(typeof(T)).Deserialize(reader);
                }
                catch (InvalidOperationException)
                {
                    // String passed is not XML, simply return defaultXmlClass
                }
            }
        }
        catch (Exception ex)
        {
        }

        return returnedXmlClass;
    }
}

And try this in your console:

        static void Main(string[] args)
    {
        var conv = new XmlToEntity();
        Root root = conv.FromXml<Root>(File.ReadAllText("data.xml"));
        Console.WriteLine(root.Products.Length.ToString());
    }

Note:

If you wish to use different queries you can use anonymous types and a little LINQ as per below:

        var query = root.Products.Select(x => new
        {
            ProductCode = x.ProductCode,
            ProductColor = x.Properties.ColorProperties.Color,
        });
Sign up to request clarification or add additional context in comments.

5 Comments

Note that you can change your entity names to anything you want. I just used the default scaffolding scenario.
My problem is I do not want create Root and Products classes, I must create just Product Class and it's necessary sub classes. So you are creating root classes etc.. this is not I want. Model must be start with Product class and this product class must have attributes that must tell the product has parents xml items Products and Root. My english not great sorry for that.
I believe the best solution is to use Root, RootProduct, etc. And if you want another type of Entity, you just create one and then Map it.
You also can use LINQ to generate different query objects. Check it out! I just updated the Answer.
Than you so much for you answer, I will wait for others opinions too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.