【发布时间】:2010-08-11 11:46:22
【问题描述】:
我正在尝试从服务器检索 XML 文档并将其作为字符串存储在本地。在桌面 .Net 中我不需要,我只是这样做了:
string xmlFilePath = "https://myip/";
XDocument xDoc = XDocument.Load(xmlFilePath);
但是在 WP7 上返回:
Cannot open 'serveraddress'. The Uri parameter must be a relative path pointing to content inside the Silverlight application's XAP package. If you need to load content from an arbitrary Uri, please see the documentation on Loading XML content using WebClient/HttpWebRequest.
所以我开始使用来自here 的 WebClient/HttpWebRequest 示例,但现在它返回了:
The remote server returned an error: NotFound.
是不是因为 XML 是 https 路径?还是因为我的路径没有以 .XML 结尾?我怎么知道?感谢您的帮助。
代码如下:
public partial class MainPage : PhoneApplicationPage
{
WebClient client = new WebClient();
string baseUri = "https://myip:myport/service";
public MainPage()
{
InitializeComponent();
client.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(
client_DownloadStringCompleted);
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
client.DownloadStringAsync
(new Uri(baseUri));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
resultBlock.Text = "Using WebClient: " + e.Result;
else
resultBlock.Text = e.Error.Message;
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(new Uri(baseUri));
request.BeginGetResponse(new AsyncCallback(ReadCallback),
request);
}
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request =
(HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 =
new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
resultBlock.Text = "Using HttpWebRequest: " + resultString;
}
}
}
【问题讨论】:
-
如果您只是将 URL 从代码中剪切并粘贴到浏览器中,您会看到什么?
-
一个 XML 页面,由 Firefox 正确格式化。像这样:w3schools.com/xml/simple.xml
标签: c# .net xml windows-phone-7