2012-08-11 46 views
3

這裏是我想要的web服務的XML提供:如何序列化從C#ASP.NET 3.5中的webservice返回的對象列表?

<business> 
    <locations> 
    <location>location 1</location> 
    <location>location 2</location> 
    </locations> 
</business> 

然而,而是下面的被返回:

<business> 
    <locations> 
    <location> 
     <name>location 1</name> 
    </location> 
    <location> 
     <name>location 2</name> 
    </location> 
    </locations> 
</business> 

下面是使用的代碼:

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Xml)] 
    public Business GetBusiness() 
    { 
     var business = new Business(); 
     business.Locations = new List<Location>(); 
     business.Locations.Add(new Location { Name = "location 1" }); 
     business.Locations.Add(new Location { Name = "location 2" }); 
     return business; 
    } 

    [XmlType(TypeName = "business")] 
    public class Business 
    { 
     [XmlArray(ElementName = "locations")] 
     [XmlArrayItem(ElementName = "location")] 
     public List<Location> Locations { get; set; } 
    } 

    [XmlType(TypeName = "location")] 
    public class Location 
    { 
     [XmlElement(ElementName = "name")] 
     public string Name { get; set; } 
    } 

如何獲得位置字符串包含位置標記而不是具有名稱標記?

TIA, 喬治

回答

3

您需要的Name部件上使用XmlTextAttribute把它當作一個XML元素的文本:

[XmlType(TypeName = "location")] 
public class Location 
{ 
    [XmlText()] 
    public string Name { get; set; } 
} 
+0

是的!這是我一直在尋找的技巧...... XmlText完美地工作,謝謝。 – 2012-08-11 20:54:03

1

爲什麼不直接使用場所的字符串列表而不是位置對象列表?

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Xml)] 
    public Business GetBusiness() 
    { 
     var business = new Business(); 
     business.Locations = new List<string>(); 
     business.Locations.Add("location 1"); 
     business.Locations.Add("location 2"); 
     return business; 
    } 

    [XmlType(TypeName = "business")] 
    public class Business 
    { 
     [XmlArray(ElementName = "locations")] 
     [XmlArrayItem(ElementName = "location")] 
     public List<string> Locations { get; set; } 
    } 

    //[XmlType(TypeName = "location")] 
    //public class Location 
    //{ 
    // [XmlElement(ElementName = "name")] 
    // public string Name { get; set; } 
    //} 

這會導致您正在查找的XML。

+0

啊,這也適用,是一個很棒的技巧要知道,謝謝。 – 2012-08-11 20:54:20

0

您可以控制使用一些在MSDN指定的方法序列化和反序列化過程:http://msdn.microsoft.com/en-us/library/ty01x675%28v=vs.80%29.aspx

在你的情況你是序列化的位置列表,使用的ElementName「位置」。如果你正在序列化字符串列表public List<string> Locations {get; set; },你會得到預期的結果。 您使用的Location對象在hiearchy中放置了一個額外的級別,因此它將自己的屬性(如name)序列化。

如果您在Locations類上實現了ISerializable接口,那麼您將完全控制生成的XML輸出,並且可以簡單地傳回「Name」屬性的內容。