問題描述
我們必須從一個 aspx 頁面中讀取數(shù)據(jù).當(dāng)我們使用查詢字符串調(diào)用頁面時,它會返回一個 xml 文檔,其中包含與查詢字符串匹配的數(shù)據(jù).
We have to read data from a aspx page. When we call the page with a query string, it returns an xml document with data that matches the query string.
我們有一個與我們返回的 xml 匹配的 XSD.
We have an XSD that matches the xml that we get back.
我認(rèn)為我們可以從 http 響應(yīng)中讀取 xml 文檔.這行得通嗎?
I am thinking that we can read the xml document out of the http response. Will this work?
我們?nèi)绾?em>綁定 XML 與 XSD,以便我們可以將 XML 文檔視為強(qiáng)類型?
How can we bind the XML with the XSD, such that we can treat the XML document as if it were strongly typed?
謝謝,
設(shè)拉子
更新:
找到這個關(guān)于如何反序列化的鏈接
Found this link on how to deserialize
在 C# 中將 XML 反序列化為對象
推薦答案
嗯,基本上,你可以請求一個類似這樣的 XML 文檔(這里沒有 try/catch - 但你絕對應(yīng)該添加它!):
Well, basically, you can request an XML document something like this (no try/catch here - but you should definitely add that!):
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST"; // or GET - depends
myRequest.ContentType = "text/xml; encoding=utf-8";
myRequest.ContentLength = data.Length;
using (Stream reqStream = myRequest.GetRequestStream())
{
// Send the data.
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
// Get Response
WebResponse myResponse;
myResponse = myRequest.GetResponse();
XmlDocument _xmlDoc = new XmlDocument();
using (Stream responseStream = myResponse.GetResponseStream())
{
_xmlDoc.Load(responseStream);
}
您有 GET 還是 POST 取決于您的場景 - 在 GET 中,您不會有請求數(shù)據(jù)輸出.
Whether you have a GET or POST depends on your scenario - in a GET, you won't have request data going out.
一旦您將 XML 作為 XmlDocument 恢復(fù),您可以根據(jù) XML 架構(gòu)對其進(jìn)行驗證,或者只是嘗試將其反序列化為您擁有的 XSD 架構(gòu)所表示的類型.
Once you have your XML back as a XmlDocument, you can either validate that against the XML schema, or just try to deserialize it into the type that is represented by the XSD schema you have.
如果可行 --> 你得到的 XML 是有效的并且沒問題.如果沒有,您將在反序列化時遇到異常.
If that works --> the XML you got is valid and OK. If not, you'll get an exception on deserialization.
馬克
這篇關(guān)于從aspx網(wǎng)頁讀取xml的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!