假设您有以下XML:
使用LINQ to XML,获取给定类型的图像的
假设您有以下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的等效方法。
有没有人能指出更好的方法?