简洁的 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 等价物时。
有人能指出更好的方法吗?
Assuming you have the following 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>
Using LINQ to XML, what is the most succinct, robust way to obtain a System.Uri
for an image of a given type? At the moment I have this:
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();
}
This works, but feels way too complicated. Especially when you consider the XPath equivalent.
Can anyone point out a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试一下:)
Give that a go :)
如果您可以保证文件始终具有相关数据,则无需进行类型检查:
如果
null
检查是优先事项(看起来确实如此):不确定您是否会变得更加简洁与
null
检查相比。If you can guarantee the file will always have the relevant data, then with no type checking:
If
null
checking is a priority (and it seems it is):Not sure if you'll get much more succinct than that with
null
checking.