只有我吗?与XPath相比,我发现LINQ to XML有点麻烦

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的内容?

And*_*erd 5

是的,你给出的例子是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)


Tim*_*ren 4

使用您感觉最舒服的方式,只要它能完成工作即可。我根据需要对 XML 执行的操作来使用这两种方法。在我看来,您已经很好地掌握了 LINQ 的优点以及 XPath 的优点。