假设你有以下的XML:简洁的LINQ to 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等价物时。
任何人都可以指出一个更好的方法吗?
+1谢谢,但它仍然比XPath等效更详细... – 2010-04-22 08:08:49