5
我正在使用API調用從Web服務器返回一些XML數據。 XML數據的格式如下:C# - 將Stream節點值設置爲來自StreamReader的Stings結果
<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>
節點值添加到字符串,但似乎無法做到這一點。我當前的代碼:試圖設置該字符串值quote
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;
}
我的程序炸彈出與型「System.NullReferenceException」未處理的異常發生。我已經看過一些類似的帖子,並進行了各種更改,但似乎無法獲得設置的兩個字符串值。
太棒了,坦克太多了!經過測試,它正在工作。我仍然正在處理XML並制定出節點/屬性/元素。 :) – Rawns