2008-11-21 67 views
5

我已經寫了一個LINQ to XML查詢來做我想做的事情,但它看起來非常難看。我想知道,你們如何格式化下面的查詢,看起來不那麼華麗呢?關於構建/格式化LINQ to XML查詢的最佳方法的建議?

道歉,如果我的例子有點冗長。

的XML文檔,我查詢有以下結構:

<?xml version="1.0" encoding="iso-8859-1"?> 
<newsitem itemid="1" id="root" date="1996-08-20" xml:lang="en"> 
    <title>A title</title> 
    <headline>A headline</headline> 
    <dateline>A dateline</dateline> 
    <text> 
     Some text 
    </text> 
    <metadata> 
     <codes class=""> 
      <code code=""> 
       <editdetail attribution=""/> 
      </code> 
     </codes> 
     <dc element="dc.date.created" value=""/> 
     <dc element="dc.publisher" value=""/> 
     <dc element="dc.date.published" value=""/> 
     <dc element="dc.source" value=""/> 
     <dc element="dc.creator.location" value=""/> 
     <dc element="dc.creator.location.country.name" value=""/> 
     <dc element="dc.source" value=""/> 
    </metadata> 
</newsitem> 

和相應的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() 
      }; 

謝謝!

+0

什麼.DefaultIfEmpty()完成? – 2009-06-15 17:28:00

回答

4

主要的「醜陋的」是底部的東西。我可能會添加一個擴展方法(或只是一個實用方法) - 是這樣的:

public static XAttribute GetMetadata(this XElement parent, string key) 
    { 
     return parent.Elements("metadata").Elements("dc") 
       .FirstOrDefault(x => x.Attribute("element").Value == key) 
       .Attribute("value"); 
    } 

,那麼你應該能夠使用類似:

Publisher = (string)article.GetMetadata("dc.publisher"); 

(未選中)