【发布时间】:2017-02-03 11:34:47
【问题描述】:
我正在使用 API 调用从 Web 服务器返回一些 XML 数据。 XML 数据格式如下:
<forismatic>
<quote>
<quoteText>The time you think you're missing, misses you too.</quoteText>
<quoteAuthor>Ymber Delecto</quoteAuthor>
<senderName></senderName>
<senderLink></senderLink>
<quoteLink>http://forismatic.com/en/55ed9a13c0/</quoteLink>
</quote>
</forismatic>
我可以成功检索原始 XML 数据,我想将 <quoteText> 和 <quoteAuthor> 节点值添加到字符串,但似乎无法做到这一点。我当前的代码:
private void btnGetQuote_Click(object sender, EventArgs e)
{
WebRequest req = WebRequest.Create("http://api.forismatic.com/api/1.0/");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string reqString = "method=getQuote&key=457653&format=xml&lang=en";
byte[] reqData = Encoding.UTF8.GetBytes(reqString);
req.ContentLength = reqData.Length;
using (Stream reqStream = req.GetRequestStream())
reqStream.Write(reqData, 0, reqData.Length);
using (WebResponse res = req.GetResponse())
using (Stream resSteam = res.GetResponseStream())
using (StreamReader sr = new StreamReader(resSteam))
{
string xmlData = sr.ReadToEnd();
txtXmlData.Text = xmlData;
Read(xmlData);
}
}
private void Read(string xmlData)
{
XDocument doc = XDocument.Parse(xmlData);
string quote = doc.Element("quote").Attribute("quoteText").Value;
string auth = doc.Element("quote").Attribute("quoteAuthor").Value;
txtQuoteResult.Text = "QUOTE: " + quote + "\r\n" + "AUTHOR: " + auth;
}
我的程序在尝试设置字符串值quote 时出现发生了“System.NullReferenceException”类型的未处理异常。我查看了一些类似的帖子并进行了各种更改,但似乎无法设置两个字符串值。
【问题讨论】:
标签: c# xml winforms streamreader