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.

6
  • 1
    What is the V class supposed to look like? Commented Aug 11, 2020 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? Commented Aug 11, 2020 at 18:28
  • This is probably what you're looking for stackoverflow.com/a/39902334/302248 Commented Aug 11, 2020 at 18:30
  • V class can be just a simple class with a string field only. Commented Aug 11, 2020 at 18:51
  • 1
    You will need to subclass List<decimal> (or Collection<decimal> if you prefer) and implement IXmlSerializable. For how, see How do you deserialize XML with dynamic element names?. In fact this may be a duplicate, agree? Commented Aug 11, 2020 at 21:41

1 Answer 1

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;
    }
}
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.