Che*_*eso 7 .net linq xpath linq-to-xml
我是一名C#程序员,所以我无法利用VB中的酷XML语法.
Dim itemList1 = From item In rss.<rss>.<channel>.<item> _
Where item.<description>.Value.Contains("LINQ") Or _
item.<title>.Value.Contains("LINQ")
Run Code Online (Sandbox Code Playgroud)
使用C#,我发现XPath比使用LINQ to XML执行多嵌套选择更容易思考,更容易编码,更容易理解.看看这个语法,它看起来像希腊语发誓:
var waypoints = from waypoint in gpxDoc.Descendants(gpx + "wpt")
select new
{
Latitude = waypoint.Attribute("lat").Value,
Longitude = waypoint.Attribute("lon").Value,
Elevation = waypoint.Element(gpx + "ele") != null ?
waypoint.Element(gpx + "ele").Value : null,
Name = waypoint.Element(gpx + "name") != null ?
waypoint.Element(gpx + "name").Value : null,
Dt = waypoint.Element(gpx + "cmt") != null ?
waypoint.Element(gpx + "cmt").Value : null
};
Run Code Online (Sandbox Code Playgroud)
所有的演员,沉重的语法,NullPointerExceptions的可能性.XPath不会发生这种情况.
我一般都喜欢LINQ,而且我在对象集合和数据库上使用它,但是我第一次查询XML时又回到了XPath.
只有我吗?
我错过了什么吗?
编辑:有人投票决定关闭这个"不是一个真正的问题".但这是一个真正的问题,清楚地说明了.问题是:我是否误解了LINQ to XML的内容?
是的,你给出的例子是unildyy.
但是使用LINQ可以灵活地重构掉unweildiness.
这是我如何改进它的一个例子.(这完全没有任何测试,我甚至不知道真正的类名,但它应该传达这个想法)
static class LinqXmlExtension
{
public static NodeThingy ElementOrNull(this XmlElement ele, string searchString)
{
return (ele.Element(searchString) != null ? ele.Element(searchString).Value : null);
}
}
//
/////////////////////////////////////////////////////////////////
var waypoints = from waypoint in gpxDoc.Descendants(gpx + "wpt")
select new
{
Latitude = waypoint.Attribute("lat").Value,
Longitude = waypoint.Attribute("lon").Value,
Elevation = waypoint.ElementOrNull(gpx + "ele"),
Name = waypoint.ElementOrNull(gpx + "name"),
Dt = waypoint.ElementOrNull(gpx + "cmt")
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
563 次 |
最近记录: |