2017-02-03 2 views
5

私はAPI呼び出しを使用してWebサーバーからXMLデータを返します。 XMLデータの形式は、次のとおりですStreamReaderの結果からStingsとして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>ノード値を追加したいが、これを行うことができないように見えます。私の現在のコード:文字列値quoteを設定しようとしているときに「System.NullReferenceException」種類の未処理の例外とアウト

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;      
    } 

私のプログラムの爆弾がを発生しました。私はいくつかの同様の投稿を見て、さまざまな変更を加えましたが、2つの文字列値を設定することはできません。

答えて

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

関連する問題