从Web服务返回XML数据

Nic*_*rca 6 c# xml web-services

创建返回一组x,y坐标的Web服务的最佳方法是什么?我不确定对象是最好的返回类型.当我使用它的服务时,我想让它以xml的形式返回,例如:

<TheData>
  <Point>
    <x>0</x>
    <y>2</y>
  </Point>
  <Point>
    <x>5</x>
    <y>3</y>
  </Point>
</TheData>
Run Code Online (Sandbox Code Playgroud)

如果有人有更好的结构返回请帮助我这一切都是新的.

Jes*_*cer 3

由于您使用的是 C#,所以这非常简单。我的代码假设您不需要反序列化,只需要一些 XML 供客户端解析:

[WebService(Namespace = "http://webservices.mycompany.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class PointService : WebService
{
    [WebMethod]
    public Points GetPoints()
    {
        return new Points(new List<Point>
        {
            new Point(0, 2),
            new Point(5, 3)
        });
    }
}

[Serializable]
public sealed class Point
{
    private readonly int x;

    private readonly int y;

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    private Point()
    {
    }

    [XmlAttribute]
    public int X
    {
        get
        {
            return this.x;
        }

        set
        {
        }
    }

    [XmlAttribute]
    public int Y
    {
        get
        {
            return this.y;
        }

        set
        {
        }
    }
}

[Serializable]
[XmlRoot("Points")]
public sealed class Points
{
    private readonly List<Point> points;

    public Points(IEnumerable<Point> points)
    {
        this.points = new List<Point>(points);
    }

    private Points()
    {
    }

    [XmlElement("Point")]
    public List<Point> ThePoints
    {
        get
        {
            return this.points;
        }

        set
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)