簡體   English   中英

從Web服務返回XML數據

[英]Return XML data from a web service

創建返回一組x,y坐標的Web服務的最佳方法是什么? 我不確定對象是最好的返回類型。 當我使用它的服務時,我想讓它以xml的形式返回,例如:

<TheData>
  <Point>
    <x>0</x>
    <y>2</y>
  </Point>
  <Point>
    <x>5</x>
    <y>3</y>
  </Point>
</TheData>

如果有人有更好的結構返回請幫助我這是新的。

由於您使用的是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
        {
        }
    }
}
<Points> <!-- alternatives: PointCollection or PointList -->
  <Point x="0" Y="2" />
  <!-- ... -->
</Points>

或者,您可以改為使用JSON表示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM