locked
xml response format issue RRS feed

  • Question

  • Hi, I am using the below controller class. How do I modify the string .ToArray() to get proper xml response format. As of everything is concatenated.

    private DbEntities db = new DbEntities();
    
            public string GetCodeText(string id)
            {
    
             if (id != null)
                {
                    var codes = (from c in db.CodeText
                                where c.Code == id
                                select new
                                {
                                    Text = c.Text
                                }).Single();
    		string result = codes.Text;
                    return result ;
                }
    	else
                {	
    		var codes = db.CodeTexts.Select(c => c.Code + "-" + c.Text).ToList();
    
    		return string.Join(",", codes.ToArray());
    		}
    }

    Desired xml format.

      <CodeText>
        <Code>ZAS32402Q4</Code>
        <Text>"This is the first record"</Text>
      </CodeText>
      <CodeText>
        <Code>DEX92898329AA</Code>
        <Text>"This is the second record"</Text>
      </CodeText>

    Thank you in advance.


    SQLEnthusiast

    Wednesday, June 22, 2016 6:04 PM

Answers

  • Hi SQLEnthusiast007,

    We could use XDocument to achieve your requirement. I create a simple demo as below for your reference.

    var codes = db.CodeTexts.Select(c => c.Code + "-" + c.Text).ToList();
                    string result = string.Join(",", codes.ToArray());
                    string[] arrayList = result.Split(',');
                    XDocument doc = new XDocument();
                    XElement root = new XElement("Root");
                    foreach (var item in arrayList)
                    {
                        string[] itemarray = item.Split('-');
                        XElement elm = new XElement("CodeText",
                         new XElement("Code", itemarray[0]),
                         new XElement("Text", itemarray[1]));
                        root.Add(elm);
                    }

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, June 23, 2016 1:23 AM