1

I'm trying to convert a c# object containing a list into XML. The list comes out fine as:

<image>dummy</image>
<image>dummy2</image>
<image>dummy3</image>

and so forth. I want the tags to be unique like:

<image_1>dummy</image_1>
<image_2>dummy2</image_2>
<image_3>dummy3</image_3>

But i'm not quite sure how to get to that result.

Any input is appreciated :)

Pac0
  • 21,465
  • 8
  • 65
  • 74
zyreex
  • 11
  • 1
  • 1
    I'd recommend not doing that, it makes it problematic to create an [XSD (xml schema)](https://en.wikipedia.org/wiki/XML_Schema_(W3C)) for your XML document. – dbc Aug 16 '20 at 16:03
  • Welcome to StackOverflow. Please share your code and provide more details about your implementation. – user35443 Aug 16 '20 at 16:03
  • 1
    A more "XML-friendly" approach would be to have a collection of elements with the same tag 'image', but with an _attribute_ that you use as a unique identifier. `dummy 1dummy 2` Could this be acceptable to you? Or else, could you explain the actual issue which made you conclude that need unique tags? (to me, it looks like a [X/Y problem](http://xyproblem.info/)) – Pac0 Aug 16 '20 at 16:05
  • @Pac0 Yea i know. It's kinda weird, but that's how the customer prefers it, so i'm just trying to give them what they want. – zyreex Aug 16 '20 at 16:09
  • ok, I don't know the details, but that sounds same thing on their side, X/Y problem. Maybe you'd do a better job (better satisfying for both your client and yourself) to udnerstand what is their actual need. Just an advice, I understand you might not have any reach on this. – Pac0 Aug 16 '20 at 16:15
  • Well, if you have to do it, you will need to serialize manually, either through `IXmlSerializable` or LINQ to XML. For the former see [How do you deserialize XML with dynamic element names?](https://stackoverflow.com/a/37262084/3744182). For the latter see [How to serialize an array to XML with dynamic tag names](https://stackoverflow.com/q/50415653/3744182). In fact I'd say this looks to be a duplicate of those two, agree? – dbc Aug 16 '20 at 16:29

1 Answers1

1

A rough sketch of a solution:

Stream stream = ... // your output stream

XmlWriter xml = new XmlWriter(stream)

xml.WriteStartDocument();

int index = 0;
foreach (var x in list) {
  xml.WriteStringElement("index_" + index++, x.ToString());
}

xml.Close();

https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlwriter?view=netcore-3.1

Moose Morals
  • 1,628
  • 25
  • 32