-1

我对.Net Web 服务编程很陌生。我在读取从 Web 服务到客户端的 XML 响应时遇到了麻烦。

在我的网络服务端:Service1.asmx.cs 代码:

    [WebMethod(Description = "substruction")]
    public double subtract(double i, double j)
    {
        return i - j;
    }


    [WebMethod(Description = "getxml")]
    public XmlDocument GetXML()
    {
        StringBuilder sb = new StringBuilder();
        XmlWriter writer = XmlWriter.Create(sb);

        writer.WriteStartDocument();
        writer.WriteStartElement("People");

        writer.WriteStartElement("Person");
        writer.WriteAttributeString("Name", "Nick");
        writer.WriteEndElement();

        writer.WriteStartElement("Person");
        writer.WriteStartAttribute("Name");
        writer.WriteValue("Kevin");
        writer.WriteEndAttribute();
        writer.WriteEndElement();

        writer.WriteEndElement();
        writer.WriteEndDocument();

        writer.Flush();

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(sb.ToString());
        return xmlDocument;

    }

在这里,我创建了两种方法来测试响应。在 GetXML 中,我创建了一个非常简单的 XML 并将一个包 XML 返回给客户端。

在我的客户端:

    // Add button click function 
    protected void Button1_Click(object sender, EventArgs e)
    {
        string selectFlag = selectOper.Value;
        localhost.Service1 web = new localhost.Service1(); // Have to be the same name as youre Service1. 
        if (selectFlag.Equals("+"))
        {
            Result.Text = (web.addition(double.Parse(Num1.Text), double.Parse(Num2.Text))).ToString();
        }
        else if (selectFlag.Equals("-"))
        {
            Result.Text = (web.subtract(double.Parse(Num1.Text), double.Parse(Num2.Text))).ToString();
        }

    }

    protected void Button2_Click(object sender, EventArgs e)
    {


        localhost.Service1 web2 = new localhost.Service1(); // Can u please do not be so silly, use different instance name here. 
        Button clickedButton = (Button)sender;

        XmlDocument xmltest = new XmlDocument();
        xmltest = web2.GetXML();

您可以看到我试图让 web2.GetXML() 将整个 XML 放入 XmlDoucment。但是,它说错误 1 ​​无法将类型“object”隐式转换为“System.Xml.XmlDocument”。存在显式转换(您是否缺少演员表?) C:\Documents and Settings\qili\My Documents\Downloads\WebService3\WebService2\WebService2\Default.aspx.cs 39 24 WebService2

任何提示,我想我做错了什么。但是 Buttom1_Click 方法工作正常。

4

2 回答 2

0

尝试转换服务的响应:

protected void Button2_Click(object sender, EventArgs e)
    {


     localhost.Service1 web2 = new localhost.Service1(); // Can u please do not be so silly, use different instance name here. 
     Button clickedButton = (Button)sender;
     XmlDocument xmltest = new XmlDocument();
     xmltest = (XmlDocument)web2.GetXML();
    }
于 2012-04-17T09:26:50.323 回答
0

您应该尝试删除服务引用,重新运行服务,然后在客户端上添加服务引用。

于 2015-11-02T07:15:25.197 回答