vb.net Linq XML Xdocument Descendants 为空

发布时间 2023-08-05 11:20:43作者: boy8199

在使用 xdocument desendants 进行筛选元素时, 发现 结果为空 

经过网友的文章提醒 发现是 命名空间 的问题

在使用linq where 进行网页元素 筛选时发现 descendants("div") 不起作用, 而是用 descendatns 可以看到元素枚举

Dim ie As IEnumerable(Of XElement) = ex1.Descendants("div").Where(Function(y) y.Attribute("class") IsNot Nothing AndAlso y.Attribute("class").Value = cName)

上面的代码 无效

网友问题提示  网页 中 使用了 命名空间   xmlns="http://www.w3.org/1999/xhtml"

div是命名空间的元素 要对该元素 添加命名空间的限定

代码修改如下

Dim ie As IEnumerable(Of XElement) = ex1.Descendants(ex1.Name.Namespace +
"div").Where(Function(y) y.Attribute("class") IsNot Nothing AndAlso y.Attribute("class").Value = cName)