从Web服务返回XML数据

时间:2010-06-08 20:14:38

标签: 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>

如果有人有更好的结构可以返回,请帮助我解决这个问题。

2 个答案:

答案 0 :(得分: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
        {
        }
    }
}

答案 1 :(得分:1)

<Points> <!-- alternatives: PointCollection or PointList -->
  <Point x="0" Y="2" />
  <!-- ... -->
</Points>

或者,你可以代替JSON代表:

[ { x:0, y:2 }, { x:5, y:10 } ]