0

I have two class :

public class Customer
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

public class myclass
{
    public string Propertie1 { get; set; }

    public Customer[] Customers { get; set; }
}   

And on instance + serializer :

myclass c = new myclass()
{
    Propertie1 = "value",

    Customers = new Customer[]
    {
        new Customer()
        {
            FirstName = "FirstName1",
            LastName = "LastName1"
        },
        new Customer()
        {
            FirstName = "FirstName2",
            LastName = "LastName2"
        }
    }
};

XmlSerializer xs = new XmlSerializer(typeof(myclass));
using (StreamWriter wr = new StreamWriter(@"c:/Temp/customers.xml"))
{
    xs.Serialize(wr, c);
}

How to add a attribute in my node for each ? for exemple

With XmlAttribute maybe ? But I don't know how to use

Thank's

1 Answer 1

1

I would do the following:

Add another property

public class Customer
{
    [XmlAttribute]
    public int id {get;set;}

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

In assinging values to the Customer object:

new Customer()
        { 
            id = 1,
            FirstName = "FirstName1",
            LastName = "LastName1"
        },

This would give the output for every customer when an id is assigned as follow

<myclass>
    <Customer id=1>
      <FirstName>FirstName1</FirstName>
      <LastName>LastName1</LastName>
    </Customer>
    <Customer id=2>
      <FirstName>FirstName2</FirstName>
      <LastName>LastName2</LastName>
    </Customer>
</myclass>

I would assume the Propertie1 in myClass will also have the [XmlAttribute] making it

<myclass Propertie1 = "<assinged value>">

This post provides a good overview

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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