0

I have an XML input as follows-

<?xml version="1.0"?>
-<INPUT>
   <V0>10.0000</V0>
   <V1>20.0000</V1> 
   <V2>30.0000</V2>
   <V3>:0.0000</V3>
   <V4>30.0000</V4>
   <V5>0.0000</V5>
   <V6>0.0000</V6>
   <V7>0.0000</V7>
   <V8>0.0000</V8>
   <V9>0.0000</V9>
   <V10>0.0000</V10>
   <V11>50.0000</V11>
   <V12>20.0000</V12>
   <V13>60.0000</V13>
   <V14>30.0000</V14>
   <V15>0.0000</V15>
   <V16>1.0000</V16>
-</INPUT>

I want to serialize it to an object for the following C# class structure-

class Input 
{
  List<V> variables; 
}

So I want to create a list for the XML elements which has pattern V[0-9]+ (e.g V0, V1, V2 and so on). The list is an ordered list to preserve the index of the variable elements. Just to mention if we can successfully serialize the mentioned XML as expected then the object should have a list of 16 items(since there are 16 XML elements with pattern V[0-9]+). The actual XML input has few hundreds variable elements.

Satyajit Dey
  • 310
  • 4
  • 7
  • 1
    What is the V class supposed to look like? – insane_developer Aug 11 '20 at 18:23
  • Sounds to me like the OP wants to read the XML data into `dynamic` (I think the `V` is meant as a generic here), and put it in a list with variable names same as the XML element names? – Sach Aug 11 '20 at 18:28
  • This is probably what you're looking for https://stackoverflow.com/a/39902334/302248 – Sach Aug 11 '20 at 18:30
  • V class can be just a simple class with a string field only. – Satyajit Dey Aug 11 '20 at 18:51
  • 1
    You will need to subclass `List` (or `Collection` if you prefer) and implement `IXmlSerializable`. For how, see [How do you deserialize XML with dynamic element names?](https://stackoverflow.com/a/37262084/3744182). In fact this may be a duplicate, agree? – dbc Aug 11 '20 at 21:41
  • Manual serialization & deserialization using LINQ to XML is also an option, see [How to serialize an array to XML with dynamic tag names](https://stackoverflow.com/q/50415653/3744182). Do either of the above two work for you? – dbc Aug 11 '20 at 22:27

1 Answers1

1

Use xml linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            Input input = new Input();
            XDocument doc = XDocument.Load(FILENAME);
            input.variables = doc.Element("INPUT").Elements().Select(x => decimal.Parse((string)x)).ToList();

        }

    }
    public class Input
    {
        public List<decimal> variables;
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20