HTML 민첩성 팩에 약간의 문제가 있습니다.
특정 노드가 포함되지 않은 HTML에서이 메서드를 사용할 때 null 참조 예외가 발생합니다. 처음에는 작동했지만 작동을 멈췄습니다. 이것은 단지 조각이며 다른 노드를 선택하는 약 10 개의 foreach 루프가 있습니다.
내가 도대체 뭘 잘못하고있는 겁니까?
public string Export(string html)
{
var doc = new HtmlDocument();
doc.LoadHtml(html);
// exception gets thrown on below line
foreach (var repeater in doc.DocumentNode.SelectNodes("//table[@class='mceRepeater']"))
{
if (repeater != null)
{
repeater.Name = "editor:repeater";
repeater.Attributes.RemoveAll();
}
}
var sw = new StringWriter();
doc.Save(sw);
sw.Flush();
return sw.ToString();
}
AFAIK, 노드가 발견되지 않으면 DocumentNode.SelectNodes
는 null
리턴 할 수 있습니다.
이것은 기본 동작입니다. codeplex의 토론 스레드 : DocumentNode.SelectNodes가 null을 반환하는 이유
따라서 해결 방법은 foreach
블록을 다시 작성하는 것입니다.
var repeaters = doc.DocumentNode.SelectNodes("//table[@class='mceRepeater']");
if (repeaters != null)
{
foreach (var repeater in repeaters)
{
if (repeater != null)
{
repeater.Name = "editor:repeater";
repeater.Attributes.RemoveAll();
}
}
}
이것은 업데이트되었으며, 이 github 이슈 에서 자세히 설명 된대로 doc.OptionEmptyCollection = true
를 설정하여 SelectNodes가 널을 리턴하지 못하게 할 수 있습니다.
이것은 쿼리와 일치하는 노드가없는 경우 null 대신 빈 컬렉션을 반환합니다 (왜 이것이 기본 동작이 아닌지 잘 모르겠습니다)