关于访问链接返回XML的获取数据

1. 返回DataSet格式;

        /// <summary>
/// 向某个url提交数据并读取该地址返回的xml,并将xml转换成dataset,并返回dataset中某个表
/// </summary>
/// <param name="url">提交的低至</param>
/// <param name="param">参数</param>
/// <param name="tableName">表名</param>
/// <param name="encoding">编码格式</param>
/// <returns></returns>
public static DataSet PostData(string url, string param, String tableName, Encoding encoding)
{
#region post数据
DataSet ds = new DataSet(); DataTable dt = new DataTable();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = ;
try
{
byte[] requestbytes = encoding.GetBytes(param);
req.Method = "post";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = requestbytes.Length;
System.IO.Stream requeststream = req.GetRequestStream();
requeststream.Write(requestbytes, , requestbytes.Length);
requeststream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream(), encoding);
String backstr = sr.ReadToEnd();
StringReader txtReader = new StringReader(backstr);
XmlTextReader xmlReader = new XmlTextReader(txtReader);
ds.ReadXml(xmlReader);
sr.Close();
res.Close();
sr.Dispose();
}
catch
{
return null;
}
//条件判断
//if (ds != null && ds.Tables.Count > 0 && ds.Tables[tableName] != null)
//{
// dt = ds.Tables[tableName].Copy();
//}
if (ds != null && ds.Tables.Count > )
{
// dt = ds.Tables[tableName].Copy();
return ds;
}
return ds;
#endregion
}

2. 返回字符串

                string url = Config.PassportUserInfoUrl + "&userid=" + userid;//可以把链接放到配置文件中
string result = SlRequest.GetResponse(url, "");
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
XmlNode node = doc.SelectSingleNode("soufun_passport/common");//选择XML节点的值
if (node != null)
{
string resMsg = node.SelectSingleNode("return_result").InnerText;
if (resMsg == "")
{
//此处可以定义一个User实体类, 来接收关于User的Inforeturn user;
}
else
{
errorMessage = node.SelectSingleNode("error_reason").InnerText;
return null;
}
//此处讲判断某个XML节点下面有几个子节点

if (node.ChildNodes.Count > 3)
                   {
                        resMsg = "";
                    }


注: C#将XMLDocument转化为String函数

       /// 将XmlDocument转化为string
/// </summary>
/// <param name="xmlDoc"></param>
/// <returns></returns>
public string ConvertXmlToString(XmlDocument xmlDoc)
{
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, null);
writer.Formatting = Formatting.Indented;
xmlDoc.Save(writer);
StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
stream.Position = ;
string xmlString = sr.ReadToEnd();
sr.Close();
stream.Close();
return xmlString;
}
上一篇:Python自动化开发 - 常用模块(一)


下一篇:Oracle索引梳理系列(二)- Oracle索引种类及B树索引