Jack
Jack

Reputation: 16724

How to Append attribute by using HtmlAgilitiPack?

I'm trying to make a new attribute in HTML tag by using HAP library:

HtmlDocument doc = new HtmlDocument();
doc.Load(PATH);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//input");
nodes[0].Attributes["foo"].Value = "baa"; /* try add 'foo' attribute with 'baa' value in input HTML element. */
doc.Save(@"C:\foo.html");

but it wiil get an exception:

Object reference not set to an instance of an object.

How to fix this?

Upvotes: 3

Views: 498

Answers (1)

Marcel N.
Marcel N.

Reputation: 13976

Yes. And .Count is nonzero

The it means the attribute first needs to be created and then added to the collection (as far as I remember since I've last used this lib):

HtmlAttribute attr = doc.CreateAttribute("foo", "baa");
nodes[0].Attributes.Add(attr);

Upvotes: 2

Related Questions