2017-02-03 21 views
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」未處理的異常發生。我已經看過一些類似的帖子,並進行了各種更改,但似乎無法獲得設置的兩個字符串值。

回答

5

您正在嘗試使用doc.Element("quote") - 沒有這樣的元素,所以返回null。你想要doc.Root.Element("quote")。接下來,你要求quoteTextquoteAuthor就好像它們是屬性 - 它們不是,它們也是元素。

所以基本上你想要的:

private void Read(string xmlData) 
{ 
    XDocument doc = XDocument.Parse(xmlData); 
    XElement quote = doc.Root.Element("quote"); 
    string text = quote.Element("quoteText").Value; 
    string author = quote.Element("quoteAuthor").Value; 
    txtQuoteResult.Text = $"QUOTE: {text}\r\nAUTHOR: {author}"; 
} 

(我親自做的方法返回的字符串值,並將其設置爲調用方法中txtQuoteResult.Text,但是這是一個不同的問題。)

+0

太棒了,坦克太多了!經過測試,它正在工作。我仍然正在處理XML並制定出節點/屬性/元素。 :) – Rawns