【问题标题】:Return XML data from a web service从 Web 服务返回 XML 数据
【发布时间】:2011-03-01 08:46:11
【问题描述】:

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

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

如果有人有更好的返回结构,请帮助我是新手。

【问题讨论】:

  • 您是否还在使用 ASMX Web 服务?如果没有,那么您应该使用 WCF。

标签: c# xml web-services


【解决方案1】:

因为您使用的是 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
        {
        }
    }
}

【讨论】:

  • 谢谢 Jesse,最后一件事是有一种简单的方法可以发布 Web 服务,以便我可以从任何地方访问?
  • 拥有空的二传手是不公平的。世界怎么会知道你只是忽略了他们的任务?为什么不将公共属性设为只读呢?甚至更好: public int X {get;私人集;}
  • 为了最简单的部署,您可以执行所谓的“XCOPY 部署”,在这种部署中,您的代码只会被复制到您网站的根目录下,用户可以通过 yoursite/service.asmx 访问它。但是,Visual Studio 本身有更强大的方法(预编译 Web、部署)将其放在 Web 服务器上。不过,您的环境可能会有所不同。
  • @SchlaWiener,正如我在序言中所说,这仅适用于序列化的 XML,并且假定不需要反序列化,因此设置器为空。
  • 我明白了,所以我必须有一个网站才能公开使用。我想可能有一个地方我可以将代码发送到他们为我发布的地方。我没有网站。
【解决方案2】:
<Points> <!-- alternatives: PointCollection or PointList -->
  <Point x="0" Y="2" />
  <!-- ... -->
</Points>

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

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

【讨论】:

  • 你能帮助一个函数签名在网络服务中创建它吗?返回什么类型?一串xml?还是有更好的方法?
  • 对不起,@Nick,我误读了你的问题。我以为你在问什么是最好的回报格式。如果您需要代码示例,@Jesse's 是一个不错的选择。
猜你喜欢
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
相关资源
最近更新 更多