开发者

Why XDocument Elements is always null

I have the following code

const string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                            <Revisions>
                                <Revision Key=""MIDTERM"">5850</Revision>
                                <Revisio开发者_如何学JAVAn Key=""LONGTERM"">5850</Revision>
                            </Revisions>";
        var key = "MIDTERM";
        var _RevisionsXml = XDocument.Parse(xml, LoadOptions.PreserveWhitespace);
        var revisionNode = _RevisionsXml
                                .Root
                                .Elements("Revision")
                                .FirstOrDefault(elem => elem.Attribute("Key").ToString() == key);

The revisionNode is always null, not sure what is that I am missing.


You want to use .Value instead of .ToString() when comparing your key.

Invoking ToString() on the attribute will return Key="MIDTERM", which is mostly used for debugging purpose.

Be sure that your XML is well formed or you could face a NullReferenceException when calling .Value if there is no attribute named Key.


You are looking for the value of the Key attribute:

var revisionNode = _RevisionsXml
                        .Root
                        .Elements("Revision")
                        .FirstOrDefault(elem => (string)elem.Attribute("Key") == key);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜