我想做的就是
node.Attributes["class"].Value但是如果节点没有class属性,它就会崩溃。所以,我必须先检查它的存在,对吧?Attributes不是一个字典(它是一个包含内部字典的列表??),也没有HasAttribute方法(只有一个HasAttributes,它表明它是否有任何属性)。我做什么好?
发布于 2010-11-04 02:16:17
已更新答案
如果缺少属性,则使用node.Attributes["class"]?.Value返回null。这将与下面的ValueOrDefault()相同。
原始答案
试试这个:
String val;
if(node.Attributes["class"] != null)
{
val = node.Attributes["class"].Value;
}或者,您可以添加以下内容
public static class HtmlAgilityExtender
{
public static String ValueOrDefault(this HtmlAttribute attr)
{
return (attr != null) ? attr.Value : String.Empty;
}
}然后使用
node.Attributes["class"].ValueOrDefault();我还没有测试过那个,但它应该可以工作。
发布于 2012-08-16 04:13:21
请尝试以下操作:
String abc = String.Empty;
if (tag.Attributes.Contains(@"type"))
{
abc = tag.Attributes[@"type"].Value;
}发布于 2016-09-20 03:53:23
此代码可用于获取两个脚本标记之间的所有文本。
String getURL(){
return @"some site address";
}
List<string> Internalscripts()
{
HtmlAgilityPack.HtmlDocument doc = new HtmlWeb().Load((@"" + getURL()));
//Getting All the JavaScript in List
HtmlNodeCollection javascripts = doc.DocumentNode.SelectNodes("//script");
List<string> scriptTags = new List<string>();
foreach (HtmlNode script in javascripts)
{
if(!script.Attributes.Contains(@"src"))
{
scriptTags.Add(script.InnerHtml);
}
}
return scriptTags;
}https://stackoverflow.com/questions/4090200
复制相似问题