Webservices:无法将类型'System.Xml.Linq.XElement'隐式转换为'System.Xml.XmlElement'

时间:2014-04-11 12:49:56

标签: c# asp.net web-services asmx

我有一个场景,我已经创建了一个Web服务,它返回通过客户端(webservice consumer)传递的用户名的名字和姓氏。

但我在第5行收到错误:无法隐式转换类型' System.Xml.Linq.XElement'到' System.Xml.XmlElement'

以下是用于检索数据的代码

protected void BindUserDetails(string userName)
    {
        UserService.ServiceSoapClient client = new UserService.ServiceSoapClient();
        DataSet dsresult = new DataSet();
       XmlElement exelement = client.GetUserDetails(userName);
        if (exelement != null)
        {
            XmlNodeReader nodereader = new XmlNodeReader(exelement);
            dsresult.ReadXml(nodereader, XmlReadMode.Auto);
            gvUserDetails.DataSource = dsresult;
            gvUserDetails.DataBind();
        }
        else
        {
            gvUserDetails.DataSource = null;
            gvUserDetails.DataBind();
        }
    }

UserService是我添加的服务引用。 gvUserDetails是gridview

[WebMethod]
    public XmlElement GetUserDetails(string username) {

        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestingCS"].ConnectionString);
        cn.Open();
        SqlCommand cmd = new SqlCommand("select * from userInfo where username=@username", cn);
        cmd.Parameters.AddWithValue("@username", username);
        cmd.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        cn.Close();
        XmlDataDocument xmldata = new XmlDataDocument(ds);
        XmlElement xmlElement = xmldata.DocumentElement;
        return xmlElement;



    } 

感谢

1 个答案:

答案 0 :(得分:2)

错误消息似乎相当清楚 - GetUserDetails正在返回XElement(从LINQ到XML)而不是XmlDocument(来自较旧的API)。

这不应该是一个问题,因为基本上你只需要选择一个元素并从中创建一个XmlReader。看起来你的代码可以改为:

protected void BindUserDetails(string userName)
{
    UserService.ServiceSoapClient client = new UserService.ServiceSoapClient();
    XElement element = client.GetUserDetails(userName);
    if (element != null)
    {
        DataSet dsresult = new DataSet();
        XmlReader reader = element.CreateReader();
        dsresult.ReadXml(reader, XmlReadMode.Auto);
        gvUserDetails.DataSource = dsresult;
    }
    else
    {
        gvUserDetails.DataSource = null;
    }
    gvUserDetails.DataBind();
}

您可以进一步重构,以提取"将XElement转换为DataSet"功能性:

// You could *consider* making this an extension method
public static DataSet ToDataSetOrNull(XElement source)
{
    if (source == null)
    {
        return null;
    }
    DataSet result = new DataSet();
    result.ReadXml(source.CreateReader(), XmlReadMode.Auto);
    return result;
}

然后您的BindUserDetails代码就是:

protected void BindUserDetails(string userName)
{
    UserService.ServiceSoapClient client = new UserService.ServiceSoapClient();
    gvUserDetails.DataSource = ToDataSetOrNull(client.GetUserDetails(userName));
    gvUserDetails.DataBind();
}

...如果你有其他的" BindXyzDetails"方法,它们同样很短。