5

我正在尝试使用 LINQ 从 ATOM 提要中的作者节点中选择“名称”字段。我可以像这样获得我需要的所有字段:

XDocument stories = XDocument.Parse(xmlContent);
XNamespace xmlns = "http://www.w3.org/2005/Atom";
var story = from entry in stories.Descendants(xmlns + "entry")
            select new Story
            {
                Title = entry.Element(xmlns + "title").Value,
                Content = entry.Element(xmlns + "content").Value
            };

在这种情况下,我将如何选择作者-> 姓名字段?

4

2 回答 2

5

你基本上想要:

entry.Element(xmlns + "author").Element(xmlns + "name").Value

但是您可能希望将其包装在一个额外的方法中,以便在缺少作者或名称元素时轻松采取适当的措施。如果有不止一位作者,您可能还想考虑您想要发生的事情。

提要也可能有作者元素……只是要记住的另一件事。

于 2008-11-18T22:42:36.373 回答
3

它可能是这样的:

        var story = from entry in stories.Descendants(xmlns + "entry")
                    from a in entry.Descendants(xmlns + "author")
                    select new Story
                    {
                        Title = entry.Element(xmlns + "title").Value,
                        Content = entry.Element(xmlns + "subtitle").Value,
                        Author = new AuthorInfo(
                            a.Element(xmlns + "name").Value,
                            a.Element(xmlns + "email").Value,
                            a.Element(xmlns + "uri").Value
                         )
                    };
于 2008-11-18T23:09:24.917 回答