使用HTMLAgilityPack节点的儿童;选择全部< P> [英] Select all <p>'s from a Node's children using HTMLAgilityPack
问题描述
我有下面的代码,我使用得到一个HTML页面。使绝对的URL,然后使链接REL nofollow的,开放的新窗口/标签。我的问题是周围的属性添加到<一个方式>
取值
I've got the following code that I'm using to get a html page. Make the urls absolute and then make the links rel nofollow and open in a new window/tab. My issue is around the adding of the attributes to the <a>
s.
string url = "http://www.mysite.com/";
string strResult = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if ((request.HaveResponse) && (response.StatusCode == HttpStatusCode.OK)) {
using (StreamReader sr = new StreamReader(response.GetResponseStream())) {
strResult = sr.ReadToEnd();
sr.Close();
}
}
HtmlDocument ContentHTML = new HtmlDocument();
ContentHTML.LoadHtml(strResult);
HtmlNode ContentNode = ContentHTML.GetElementbyId("content");
foreach (HtmlNode node in ContentNode.SelectNodes("/a")) {
node.Attributes.Append("rel", "nofollow");
node.Attributes.Append("target", "_blank");
}
return ContentNode.WriteTo();
任何人都可以看到我在做什么错?去过尝试了一段时间这里没有运气。此代码出现该ContentNode.SelectNodes(/ a)的未设置为一个对象的一个实例。我虽然尝试和蒸汽设置为0?
Can anyone see what I'm doing wrong? Been try for a while here with no luck. This code comes up that ContentNode.SelectNodes("/a") isn't set to an instance of an object. I though to try and set the steam to 0?
干杯,
丹尼斯
Cheers, Denis
推荐答案
是 ContentNode
空?您可能需要选择单与查询// * [@ ID ='内容']
。
Is ContentNode
null? You might need to select-single with the query "//*[@id='content']"
.
有关信息, 一
表示所有锚在根。确实后裔::一个
工作?还有 HtmlElement.GetElementsByTagName
这可能是更容易 - 即 yourElement.GetElementsByTagName(A)
For info, "/a"
means all anchors at the root. does "descendant::a"
work? There is also HtmlElement.GetElementsByTagName
which might be easier - i.e. yourElement.GetElementsByTagName("a")
.
这篇关于使用HTMLAgilityPack节点的儿童;选择全部< P>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!