我编写了一个LINQ to XML查询,它可以实现我想要的功能,但它看起来非常难看.我想知道,你们怎么会以一种看起来不那么花哨的方式格式化以下查询?
如果我的例子有点冗长,请道歉.
我查询的XML文档具有以下结构:
A title A headline A dateline Some text
和相应的LINQ查询:
XElement dummy = new XElement("dummy"); var query = from article in newsdoc.Elements("newsitem").DefaultIfEmpty(dummy) select new { NewsItemID = (int)article.Attribute("itemid"), Date = (DateTime)article.Attribute("date"), Title = (string)article.Element("title"), Headline = (string)article.Element("headline"), ByLine = (string)article.Element("byline"), DateLine = (string)article.Element("dateline"), NewsText = (string)article.Element("text"), Publisher = (string)article.Elements("metadata").Elements("dc").Where(x => (string)x.Attribute("element") == "dc.publisher").Attributes("value").DefaultIfEmpty().ElementAt(0), DatePublished = (DateTime)article.Elements("metadata").Elements("dc").Where(x => (string)x.Attribute("element") == "dc.date.published").Attributes("value").DefaultIfEmpty().ElementAt(0), Source = (string)article.Elements("metadata").Elements("dc").Where(x => (string)x.Attribute("element") == "dc.source").Attributes("value").DefaultIfEmpty().ElementAt(0), CreatorLocation = (string)article.Elements("metadata").Elements("dc").Where(x => (string)x.Attribute("element") == "dc.creator.location").Attributes("value").DefaultIfEmpty().ElementAt(0), CreatorLocationCountryName = (string)article.Elements("metadata").Elements("dc").Where(x => (string)x.Attribute("element") == "dc.creator.location.country.name").Attributes("value").DefaultIfEmpty().ElementAt(0), Codes = article.Elements("metadata").Elements("codes").Elements("code").Attributes("code").DefaultIfEmpty() };
谢谢!