WCF - same name tags in xml response

2019-09-01 02:59发布

问题:

I am a newbie. Plzz help me at this. In WCF rest application i want the following response

<parameterList>    
        <parameter>        
            <Question> Occupation </Question> 

            <Choice> Student/Others </Choice>      
            <Choice> Retired/housewife </Choice>       
            <Choice> Salaried/SelfEmployed </Choice>        
            <Choice> Doctor/CA/Socially Important Person </Choice> 

        </parameter>    
</parameterList>

I want 4 same "choice" tags with different contents. What i am getting is only the last "choice" tag.

IService.cs

[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/getQuestion")]
[return: MessageParameter(Name = "parameterList")]
List<parameter> getQuestion();

Service.svc.cs

public List<parameter> getQuestion()
    {
        List<parameter> lstParameter = new List<parameter>();
        parameter param = new parameter();
        param.Question = " Occupation ";
        param.Choice = " Student/Others ";
        param.Choice = " Retired/housewife ";
        param.Choice = " Salaried/SelfEmployed ";
        param.Choice = " Doctor/CA/Socially Important Person ";
        lstParameter.Add(param);
        return lstParameter;
    }

parameter.cs

public class parameter
{
    public string Question
    {
        get{ } set{ }
    }

    public string Choice
    {
        get{ } set{ }
    }
}

回答1:

Solved It

        [XmlElement("Choice")]

        public List<string> Choice
        {
            get { return aChoice; }
            set { aChoice = value; }
        }

Just needed to add [XmlElement("")] above the property to rename the Xml Element.

Thanx james. u were helpful.



回答2:

You keep overriding Choice with a new string. Your Choice property needs to be a List

   public List<string> Choice
        {
            get { return new List<string>();}
        }

then you can add to the list

param.Choice.add(" Occupation ");
param.Choice.add(" Retired/housewife ");

etc....

After that you would have to loop through all the choices and add them to you XML