1

I have an array with elements and want to have an iteration in the names of the elements when using Serialization in C#.

Let's say I have the class:

class MyClass {
    public int[] MyArray { get; set; }
}

Currently the xml build with Serialization looks like this:

<MyClass>
    <MyArray>
        <int>1</int>
        <int>2</int>
        ...
    </MyArray>
</MyClass>

But I need it to look like this:

<MyClass>
    <MyArray>
        <int1>1</int1>
        <int2>2</int2>
        ...
    </MyArray>
</MyClass>

I want to communicate with another system which don't allow two elements with the same XML-path, so the default Serialization isn't possible.

I know I can use Annotations like [XmlArrayItem("int")], but I don't think it's possible to name the elements of the array different.

Worst case I have to implement the IXmlSerializable interface, but that would be a lot of work, because basically then I have to write the complete Serialization by myself with reflection.

So if anyone has an idea how to iterate the names of array elements with Annotation or any other hack, I would be very happy!

Solution: I used the solution from the similar question How do you deserialize XML with dynamic element names?. I changed it a bit for my problem, but now it's working! Thanks for the comments and tips!

  • 2
    No, you don't need to. Don't do such tag naming! Those who will then parse your xml will curse you. – Alexander Petrov Sep 11 '20 at 21:12
  • I'm the one programming the other system. But there i only can read data by using the xml-path, and if i want all elements of the array, they must have different names. – PrivacyCookie Sep 11 '20 at 21:28
  • That's a very broken XML design. If you have control over the receiving system, you should probably change that to support multiple tags with the same name. Why aren't you using standard XML deserialization on the receiving side? – itsme86 Sep 11 '20 at 21:31
  • Yes, I know that's very bad design, but it's not mine and I can't change it. I have to use an interface and there are only a few methods given. – PrivacyCookie Sep 11 '20 at 21:34
  • You can user XmlSerializer : https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.ixmlserializable?view=netcore-3.1 – jdweng Sep 11 '20 at 22:11
  • 2
    In xpath you can you access by index: `/int[i]`. No need to different names. – Alexander Petrov Sep 11 '20 at 22:15
  • 1
    I think a better design is to use an additional attribute. Like as `1` – Alexander Petrov Sep 11 '20 at 22:20
  • I agree with other commenters: don't do this! But if you have to do it, it looks to be a duplicate of [How do you deserialize XML with dynamic element names?](https://stackoverflow.com/q/37255149/3744182) or [How to serialize an array to XML with dynamic tag names](https://stackoverflow.com/q/50415653/3744182). Agree? – dbc Sep 12 '20 at 00:50

0 Answers0