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 следующие:
<Items>
<Item>
<Id></Id>
<Name></Name>
<Description></Description>
<Price></Price>
</Item>
</Items>
Идентификатор и цена являются оба целочисленными значениями. Имя и описание являются строками.
Я нашел Linq to XML
большой для того, для чего я использовал его, это - просто отрывок. Но, с другой стороны, я получаю чувство, что это должно или могло быть более чистым. Кастинг кажется самой очевидной проблемой в этом отрывке.
Совет?
На самом деле было бы лучше лишить, чем позвонить Int.Parse
. Вот как я бы написал ваш запрос:
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")
};
В вашем примере вы можете немного подобрать, найдя элемент <элемент />
, а не
, чтобы избежать получения родителей
каждый раз:
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)
};
Рассмотрим, как написать новый конструктор для PurbeiteTem
, который принимает элемент XML, так что вы можете написать:
select new PurchaseItem(item.Parent);
Я предполагаю, что у вас также есть узлы «предметов»?
Вы можете сделать что-то вроде этого, предполагая, что вы загружаете документ, используя xelement.load.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)
};
не Намного лучше, но намного легче читать!