Linq To Xml 备忘录3(使用Namespace的查询)

刚在CSDN上回答了一个问题,感觉蛮有代表性。所以在这里开题说说。

有这样的一个XML(实际上一个RSS Feed)

Linq To Xml 备忘录3(使用Namespace的查询)

需要查找其中rel= "self" 和 "alternate"以外并且type='application/atom+xml'的link节点,取出其中的href。研究一下这个Xml结构,一般用Xpath只要查找根下的所有link,再用Attribute排除掉不想要的就可以了: "//link[@rel<>'self' and @rel<>'alternate' and @type='application/atom+xml']"

其实没这么简单,注意一下 feed 节点: <feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'> 。这表明该节点下所有子节点除了openSearch节点外都存在这个命名空间下面。(因为子节点没有指定其他命名空间,openSearch指定了另一namespace)。BTW:节点的命名空间的,还可以通过别名来指定。比如:

<bookstore xmlns:ab="urn:newbooks-schema">
<ab:book genre="novel" style="hardcover">
<title>The Handmaid's Tale</title>
<author>
<first-name>Margaret</first-name>
<last-name>Atwood</last-name>
</author>
<price>19.95</price>
</ab:book>
</bookstore>
回到Linq2Xml的话题,对于这样有namespace的XML,就必须在代码里指定要查询节点的Namespace。代码如下:

XElement data = XElement.Load(@"XML文件路径"); XNamespace ns = "http://www.w3.org/2005/Atom"; var result = from item in data.Descendants(ns + "link") where item.Attribute("rel").Value != "self" && item.Attribute("rel").Value != "alternate" && item.Attribute("type").Value == "application/atom+xml" select new { rel = item.Attribute("rel").Value, type = item.Attribute("type").Value, href = item.Attribute("href").Value };

先定义了 XNamespace,然后在查询中使用: ns + "link"。这样就能正确查出想要的节点了。