2010-01-28 56 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") 
      };