2010-01-28 60 views
6
var subset = from item in document.Descendants("Id") 
      where item.Value == itemId.ToString() 
      select new PurchaseItem() { 
       Id = int.Parse(item.Parent.Element("Id").Value), 
       Name = item.Parent.Element("Name").Value, 
       Description = item.Parent.Element("Description").Value, 
       Price = int.Parse(item.Parent.Element("Price").Value) 
      }; 

的XML的結構如下:Linq-XML總是如此混亂嗎?

<Items> 
    <Item> 
     <Id></Id> 
     <Name></Name> 
     <Description></Description> 
     <Price></Price> 
    </Item> 
</Items> 

標識,和價格都是整數值。名稱和描述是字符串。

我發現Linq to XML非常適合我使用它,這只是一個片段。但另一方面,我感覺它應該或可能更清潔。該演員似乎是這個片段中最明顯的問題。

有什麼建議嗎?

+1

嘗試使用XmlReader,甚至是舊的XML DOM,你將重新評估你的'凌亂'的觀點。 ;) – Noldorin 2010-01-28 22:26:04

+0

這裏的語法在動態方面會非常乾淨。想象一下'ID = item.Id'等 – 2010-01-28 22:26:11

+0

@Noldorin - 'untidy'會比較適合;)我過去使用過XMLReader,現在很亂。 – Finglas 2010-01-28 22:37:10

回答

13

事實上,它會比鑄造int.Parse更好。這是我會怎麼寫你的查詢:

var subset = from item in document.Descendants("Item") 
      where item.Element("Id").Value == itemId.ToString() 
      select new PurchaseItem() 
         { 
          Id = int.Parse(item.Element("Id").Value), 
          Name = item.Element("Name").Value, 
          Description = item.Element("Description").Value, 
          Price = int.Parse(item.Element("Price").Value) 
         }; 
+2

男人,你很快.... – 2010-01-28 22:11:04

+0

約翰,任何評論爲什麼doint這種方式,而不是我顯示它的方式? – 2010-01-28 22:15:09

+0

@Jon - 爲什麼.Value不是必需的?這是隱含在幕後嗎? – Finglas 2010-01-28 22:39:44

1

我假設你還有一個「Items」節點?

你可以做這樣的事情,假設你正在使用加載XElement.Load()文檔

var subset = from item in document.Elements("Item") 
      where item.Element("Id").Value == itemId.ToString() 
      select new PurchaseItem() { 
       Id = int.Parse(item.Element("Id").Value), 
       Name = item.Element("Name").Value, 
       Description = item.Element("Description").Value, 
       Price = int.Parse(item.Element("Price").Value) 
      }; 

不是好了很多,但更容易閱讀!

1

在您的例子,你可以通過查找<Item/>元素,而不是<Id/>避免每次得到Parent整理了一點點爲需要XML元素的PurchaseItem寫一個新的構造函數,所以你可以這樣寫:

select new PurchaseItem(item.Parent); 
+0

我原本有這個,但在玩代碼後改變了它。所以+1給我展示它可以做到。 – Finglas 2010-01-28 22:20:02

1

考慮:

string id = itemId.ToString(); // We don't need to convert it each time! 

var subset = from item in document.Descendants("Id") 
      where item.Value == id 
      let parent = item.Parent 
      select new PurchaseItem 
      { 
       Id = (int) parent.Element("Id"), 
       Name = (string) parent.Element("Name"), 
       Description = (string) parent.Element("Description"), 
       Price = (int) parent.Element("Price") 
      };