2012-08-10 64 views
3

我在C#中玩弄this simple tutorial,這裏是你可以獲得的XML。如何格式化REST Web服務的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"?> 
+1

添加doctype是可能的,但需要一些編碼 - 請參閱http://shevaspace.blogspot.co.uk/2009/01/include-xml-declaration-in-wcf-restful.html。對於1)你必須重寫XmlSerialization – dash 2012-08-10 16:17:37

+0

感謝@Dash,你的鏈接是非常值得的 – user1589780 2012-08-13 13:34:14

回答

0

所以,這裏是我做過什麼來解決這個問題。該解決方案不涉及序列化,但至少可以根據需要設置響應的格式。

  • (1)將System.xml.linq中的XElement作爲每個方法的返回類型,並在每個方法中使用XElement類構建xml。
  • (2)正確使用 the code provided here在xml響應之上添加xml聲明。感謝@Dash的鏈接。
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 
    } 
+0

問題是我不處理文檔...返回類型的GetPerson()是人。該服務返回一個Person,但在發送之前構建xml。那麼我應該在哪裏使用這種類型的代碼? – user1589780 2012-08-13 09:24:21

+0

好吧,我並沒有真正明白,但也許這篇文章會幫助你:http://stackoverflow.com/a/11897491/1522782 – 2012-08-13 10:48:03

+0

有用嗎? @ user1589780 – 2012-08-13 12:16:30