假设您有以下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等效时。
有人能指出更好的方法吗?
答案 0 :(得分:1)
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();
给它一个去:)
答案 1 :(得分:1)
return xml.XPathSelectElements(string.Format("//image[info/imageType='{0}']/imagedata/@fileref",imageType))
.Select(u=>new Uri(u.Value)).FirstOrDefault();
答案 2 :(得分:0)
如果您可以保证文件始终具有相关数据,则不进行类型检查:
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
检查更简洁。