asp.net使用DataSet的ReadXml读取XML文件及Stream流的方法
本文实例讲述了asp.net使用DataSet的ReadXml读取XML文件及Stream流的方法。分享给大家供大家参考,具体如下:
stringstrxml="<xml><m><a>1</a><b>2</b></m><m><a>11</a><b>22</b></m><m><a>111</a><b>222</b></m></xml>"; DataSetds=newDataSet(); Streamstream=newMemoryStream(Encoding.Default.GetBytes(strxml)); ds.ReadXml(stream); GridView1.DataSource=ds; GridView1.DataBind();
protectedvoidPage_Load(objectsender,EventArgse) { if(!IsPostBack) { DataSetds=newDataSet(); TextReaderreader=newStringReader(@" <music> <song> <artist>TheChi-lites</artist> <genre>Soul</genre> <album>Alonelyman</album> <year>1972</year> </song> <song> <artist>Babyface</artist> <genre>R&B</genre> <album>unknown</album> <year></year> </song> <song> <artist>Babyface</artist> <genre>R&B</genre> <album>Theessentialbabyface</album> <year>2001</year> </song> <song> <artist>Babyface</artist> <genre>R&B</genre> <album>Grownandsexy</album> <year>2005</year> </song> <song> <artist>MariaArredondo</artist> <genre>Pop</genre> <album>Notgoingunder</album> <year>2004</year> </song> <song> <artist>LeonaLewis</artist> <genre>Pop</genre> <album>Unknown</album> <year>2008</year> </song> <song> <artist>Usher</artist> <genre>R&B</genre> <album>Usher</album> <year>2008</year> </song> <song> <artist>ChristinaAguilera</artist> <genre>Blues</genre> <album>Backtobasics</album> <year>2004</year> </song> <song> <artist>Sting</artist> <genre>Pop</genre> <album>Shapeofmyheart</album> <year></year> </song> </music> "); //读取Xml字符串用来接收WebService返回数据 ds.ReadXml(reader,XmlReadMode.Auto); //生成Xml文件 //ds.WriteXml(Server.MapPath("xml/song_bak.xml")); GridView1.DataSource=ds; GridView1.DataBind(); } }
#region接口返回的Xml转换成DataSet ///<summary> ///返回的Xml转换成DataSet ///</summary> ///<paramname="text">Xml字符</param> ///<returns></returns> privateDataSetGetDataSet(stringtext) { try { XmlTextReaderreader=newXmlTextReader(newStringReader(text)); reader.WhitespaceHandling=WhitespaceHandling.None; DataSetds=newDataSet(); ds.ReadXml(reader); reader.Close(); ds.Dispose(); returnds; } catch { returnnull; } } #endregion #region后台提交数据且获取接口返回的数据 ///<summary> ///后台提交数据且获取接口返回的数据 ///</summary> ///<paramname="relativePath">地址</param> ///<returns></returns> publicstaticstringGetRequestString(stringrelativePath) { stringrequestUrl=relativePath; try { //创建一个HTTP请求 HttpWebRequestrequest=(System.Net.HttpWebRequest)WebRequest.Create(requestUrl); request.Method="GET"; StreamReaderjsonStream=newStreamReader(request.GetResponse().GetResponseStream()); stringjsonObject=jsonStream.ReadToEnd(); returnjsonObject; } catch { returnstring.Empty; } } #endregion
更多关于asp.net相关内容感兴趣的读者可查看本站专题:《asp.net操作json技巧总结》、《asp.net字符串操作技巧汇总》、《asp.net操作XML技巧总结》、《asp.net文件操作技巧汇总》、《asp.netajax技巧总结专题》及《asp.net缓存操作技巧总结》。
希望本文所述对大家asp.net程序设计有所帮助。