Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Setting XML Node values as Stings from StreamReader result

I'm using an API call to return some XML data from a web server. The XML data is in the following format:

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

I can retrieve the raw XML data successfully, and I want to add the <quoteText>and <quoteAuthor> node values to strings but seem to be unable to do this. My current code:

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

My program bombs out with An unhandled exception of type 'System.NullReferenceException' occurred while trying to set the string value quote. I've looked at some similar posts and made various changes but can't seem to get the two string values set.

like image 733
Rawns Avatar asked Feb 03 '17 11:02

Rawns


1 Answers

You're trying to use doc.Element("quote") - there's no such element, so that's returning null. You'd want doc.Root.Element("quote"). Next you're asking for quoteText and quoteAuthor as if they were attributes - they're not, they're elements too.

So basically you want:

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

(I'd personally make the method return the string value and set it as txtQuoteResult.Text within the calling method, but that's a different matter.)

like image 143
Jon Skeet Avatar answered Oct 11 '22 09:10

Jon Skeet