-1

I am developing a simple Web API with only GET controller. Currently,I have the following model, which is the return type of my GET controller:

namespace _1WebApplication.Models
{
    [DataContract]
    public class SystemStatus
    {        
        public string SystemName { get; set; }       
        public string Good { get; set; }      
        public string Bad { get; set; }        
        public string MachineStatus { get; set; }
    }
}

and my GET api looks like this:

// GET api/values
public SystemStatus Get()
{
    //Read the data from XML file here
    string systemName = "REW_1";
    string good = "60";
    string bad = "10";
    string machineStatus = "Running";

    var SystemStatus = new SystemStatus
    {
        SystemName = systemName,
        Good = goodCount,
        Bad = badCount,
        MachineStatus = machineStatus
    };

    return SmartscanStatus;    
}

QUESTION: In the above case, I can return the values of only 4 variables (i.e. SystemName , Good , Bad and MachineStatus ). But actually, I want to read the parameters and values from an XML file and then return those values.

For example, I have this XML file

<SystemName>mysystem</SystemName>
<Good>60</Good>
<Bad>10</Bad>
<MachineStatus>stop</MachineStatus>
<IpAddress>127.0.0.1</IpAddress>        
<Username>username</Username>       
<Password>password</Password> 

In this case, the XML file has some more variable but since my model is fixed, I am not able to return them. So, how to make my model flexible/dynamic so that I can decide the variable names and values from an XML file.

skm
  • 5,015
  • 8
  • 43
  • 104

1 Answers1

-1

Read the XML with XDocument and convert it into dynamic object

ExpandoObject provides a way to construct dynamic properties.

public SystemStatus Get()
{
    XDocument xmlDoc = XDocument.Parse(xmlData); 
    string jsonStr = JsonConvert.SerializeXNode(xmlDoc);
    dynamic dynamicObject = JsonConvert.DeserializeObject<ExpandoObject>(jsonStr);

    return dynamicObject;
}
Hary
  • 5,690
  • 7
  • 42
  • 79