[英]Succinct LINQ to XML Query
假設您有以下XML:
<?xml version="1.0" encoding="utf-8"?>
<content>
<info>
<media>
<image>
<info>
<imageType>product</imageType>
</info>
<imagedata fileref="http://www.example.com/image1.jpg" />
</image>
<image>
<info>
<imageType>manufacturer</imageType>
</info>
<imagedata fileref="http://www.example.com/image2.jpg" />
</image>
</media>
</info>
</content>
使用LINQ to XML,獲得給定類型圖像的System.Uri
最簡潔,最健壯的方法是什么? 目前我有這個:
private static Uri GetImageUri(XElement xml, string imageType)
{
return (from imageTypeElement in xml.Descendants("imageType")
where imageTypeElement.Value == imageType && imageTypeElement.Parent != null && imageTypeElement.Parent.Parent != null
from imageDataElement in imageTypeElement.Parent.Parent.Descendants("imagedata")
let fileRefAttribute = imageDataElement.Attribute("fileref")
where fileRefAttribute != null && !string.IsNullOrEmpty(fileRefAttribute.Value)
select new Uri(fileRefAttribute.Value)).FirstOrDefault();
}
這有效,但感覺太復雜了。 特別是當您考慮XPath等效時。
任何人都能指出更好的方法嗎?
var images = xml.Descentants("image");
return images.Where(i => i.Descendants("imageType")
.All(c => c.Value == imageType))
.Select(i => i.Descendants("imagedata")
.Select(id => id.Attribute("fileref"))
.FirstOrDefault())
.FirstOrDefault();
給那個去吧:)
return xml.XPathSelectElements(string.Format("//image[info/imageType='{0}']/imagedata/@fileref",imageType))
.Select(u=>new Uri(u.Value)).FirstOrDefault();
如果您可以保證文件始終具有相關數據,則不進行類型檢查:
private static Uri GetImageUri(XElement xml, string imageType)
{
return (from i in xml.Descendants("image")
where i.Descendants("imageType").First().Value == imageType
select new Uri(i.Descendants("imagedata").Attribute("fileref").Value)).FirstOrDefault();
}
如果null
檢查是優先級(它似乎是):
private static Uri GetSafeImageUri(XElement xml, string imageType)
{
return (from i in xml.Descendants("imagedata")
let type = i.Parent.Descendants("imageType").FirstOrDefault()
where type != null && type.Value == imageType
let attr = i.Attribute("fileref")
select new Uri(attr.Value)).FirstOrDefault();
}
不確定你是否會比使用null
檢查更簡潔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.