3

这是我希望 Web 服务提供的 XML:

<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,乔治

4

3 回答 3

3

您需要使用成员上的XmlTextAttributeName将其视为 XML 元素的文本:

[XmlType(TypeName = "location")]
public class Location
{
    [XmlText()]
    public string Name { get; set; }
}
于 2012-08-11T20:38:59.387 回答
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。

于 2012-08-11T20:45:14.990 回答
0

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

在您的情况下,您正在使用 ElementName“位置”序列化位置列表。如果您正在序列化字符串列表,public List<string> Locations {get; set; }您将获得预期的结果。您使用的 Location 对象在层次结构中放置了一个额外的级别,因此使用它自己的属性(如名称)自行序列化。

如果您ISerializable在类上实现接口Locations,您将完全控制生成的 XML 输出,并且可以简单地传回您的“名称”属性的内容。

于 2012-08-11T20:55:00.307 回答