2

I have a class

public class clsTest
{
     public string name;

    [XmlArray(ElementName = "values")]
    [XmlArrayItem(ElementName = "value")]
    public float[] values;

    public clsTest()
    {
        name = "name-test";
        values = new float[4];
        values[0] = 0.9F;
        values[1] = 1.1F;
        values[2] = 2.2F;
        values[3] = 3.3F;
    }
}

When I serialize the class I get:

<clsTest>
    <name>name-test</name>

    <values>
          <value>0.9</value>
          <value>1.1</value>
          <value>2.2</value>
          <value>3.3</value>
    </values>

</clsTest>

I want to serialize the class and have array index in the XML output as Attribute. I would like something like this:

<clsTest>
    <name>name-test</name>

    <values>
      <value index="0">0.9</value>
      <value index="1">1.1</value>
      <value index="2">2.2</value>
      <value index="3">3.3</value>
    </values>
</clsTest>

How could I achieve this?

Fabiano
  • 5,124
  • 6
  • 42
  • 69

1 Answers1

0

There's no magic that will do this for you. The only way you're going to get that output is if you have an object structure that looks like that. For example:

public class ClsTest
{
    [XmlElement("name")]
    public string Name { get; set; }

    [XmlArray("values")]
    [XmlArrayItem("value")]
    public IndexedFloat[] Values { get; set; }
}

public class IndexedFloat
{
    [XmlAttribute("index")]
    public int Index { get; set; }

    [XmlText]
    public float Value { get; set; }
}

You could add another property allow you to easily get and set the raw float values:

[XmlIgnore]
public IEnumerable<float> ValuesRaw
{
    get { return Values.Select(x => x.Value); }
    set
    {
        Values = value
            .Select((x, i) => new IndexedFloat {Index = i, Value = x})
            .ToArray();
    }
}

You can see in this fiddle that you get the output you want.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
  • The elemtns in the array are indexed. There is NO way to get the information in the serialization output ? I don't want magic. I want to get the index in the array – Antonis Paparis Jul 13 '17 at 06:55
  • And that would be magic - there's no feature that adds attributes based on an index. You can do it his way, or you manually implement `IXmlSerializable`. – Charles Mager Jul 13 '17 at 06:59