C# - 将XML节点值设置为来自StreamReader结果的Stings

Raw*_*wns 5 c# xml streamreader winforms

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

我可以成功检索原始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;                    
    }
Run Code Online (Sandbox Code Playgroud)

我的程序在尝试设置字符串值时发生了"System.NullReferenceException"类型的未处理异常quote.我看了一些类似的帖子并进行了各种更改,但似乎无法获得两个字符串值设置.

Jon*_*eet 5

你正试图使用doc.Element("quote")- 没有这样的元素,所以返回null.你想要的doc.Root.Element("quote").接下来你要求quoteText并且quoteAuthor好像它们是属性 - 它们不是,它们也是元素.

所以基本上你想要:

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}";
}
Run Code Online (Sandbox Code Playgroud)

(我个人使该方法返回字符串值并将其设置为txtQuoteResult.Text调用方法,但这是另一回事.)