Skip to content

HtmlNode.GetEncapsulatedData fails when target property is a nullable value type #510

@elgonzo

Description

@elgonzo

1. Description

HtmlNode.GetEncapsulatedData throws an exception when properties of some nullable value type should be populated.

2. Exception

Unhandled exception. System.Exception: Unhandled Exception : Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int32, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]'.
   at HtmlAgilityPack.HtmlNode.GetEncapsulatedData(Type targetType, HtmlDocument htmlDocument) in C:\Repos\HtmlAgilityPack\HtmlAgilityPack.Shared\HtmlNode.Encapsulator.cs:line 224
   at HtmlAgilityPack.HtmlNode.GetEncapsulatedData[T]() in C:\Repos\HtmlAgilityPack\HtmlAgilityPack.Shared\HtmlNode.Encapsulator.cs:line 36

3. Fiddle or Project

https://dotnetfiddle.net/6JUCcn

[HasXPath]
public class Model
{
    [XPath("div", "foo")]
    public int? NullableInt {get;set;}
}

					
string html = @"<div foo=""42"">Hello world!</div>";
		
var doc = new HtmlDocument();
doc.LoadHtml(html);
var m = doc.DocumentNode.GetEncapsulatedData<Model>();
		
Console.WriteLine($"m.NullableInt = {m.NullableInt}");

4. Any further technical details

HAP 1.11.50
.NET 7
(as per dotnetfiddle demo linked above)

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions