如何格式化REST Web服务的XML响应?

时间:2012-08-10 15:17:13

标签: c# xml web-services rest

我正在使用C#中的this simple tutorial,这里有你可以获得的XML。

    <Person xmlns="http://schemas.datacontract.org/2004/07/RESTfulDemo" 
      xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <Age>23</Age>
      <ID>1</ID>
      <Name>Bob Kohler</Name>
    </Person>

这是Person.cs类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Runtime.Serialization;

    namespace RESTfulDemo
    {   

      [DataContract]
      public class Person
      {
         [DataMember]
         public string ID;

         [DataMember]
         public string Name;

         [DataMember]
         public string Age;
      }
    }

1)我应该如何在XML中为每个数据成员添加属性/前缀?

2)如何将XML的标题设置为此(或其他任何内容):

    <?xml version="1.0"?>

2 个答案:

答案 0 :(得分:0)

问题2)可以在初始化文档时完成:

XDocument document = new XDocument(new XDeclaration("1.0", "utf-16", "yes"));

问题1),根据我的理解,如果你有这样的XML文件:

<CATALOG>
  <CD>
    <TITLE> ... </TITLE>
    <ARTIST> ... </ARTIST>
    <YEAR> ... </YEAR>
  </CD>
</CATALOG>

您需要为"id"节点添加属性CD,                (其中id自动递增)

XmlNodeList list = document.GetElementsByTagName("CATALOG");
int i = 0;

foreach (XmlNode CD in list)
  {
    i++;
    XmlAttribute idAttr = document.CreateAttribute("id");
    idAttr.Value = i.ToString();
    CD.Attributes.Append(idAttr); //to append the created attribute and its value to the CD node
  }

答案 1 :(得分:0)

所以,这就是我为克服这个问题所做的工作。该解决方案不涉及序列化,但至少可以根据需要格式化响应。

  • (1)将System.xml.linq中的XElement作为每个方法的返回类型,并在每个方法中使用XElement类构建xml。
  • (2)准确使用 the code provided here 在xml响应之上添加xml声明。感谢@Dash的链接。
相关问题