HTML 예제 :
<html><body>
<form id="form1">
<input name="foo1" value="bar1" />
<!-- Other elements -->
</form>
<form id="form2">
<input name="foo2" value="bar2" />
<!-- Other elements -->
</form>
</body></html>
테스트 코드 :
HtmlDocument doc = new HtmlDocument();
doc.Load(@"D:\test.html");
foreach (HtmlNode node in doc.GetElementbyId("form2").SelectNodes(".//input"))
{
Console.WriteLine(node.Attributes["value"].Value);
}
doc.GetElementbyId("form2").SelectNodes(".//input")
문 doc.GetElementbyId("form2").SelectNodes(".//input")
는 나에게 null 참조를 제공합니다.
내가 잘못 한게있어? 감사.
다음을 수행 할 수 있습니다.
HtmlNode.ElementsFlags.Remove("form");
HtmlDocument doc = new HtmlDocument();
doc.Load(@"D:\test.html");
HtmlNode secondForm = doc.GetElementbyId("form2");
foreach (HtmlNode node in secondForm.Elements("input"))
{
HtmlAttribute valueAttribute = node.Attributes["value"];
if (valueAttribute != null)
{
Console.WriteLine(valueAttribute.Value);
}
}
기본적으로 HTML Agility Pack은 다른 HTML 요소와 겹치기 때문에 양식을 빈 노드로 구문 분석합니다. 첫 번째 행 ( HtmlNode.ElementsFlags.Remove("form");
)은이 동작을 비활성화하여 두 번째 형식의 입력 요소를 가져올 수있게합니다.
업데이트 : 양식 요소 겹침의 예 :
<table>
<form>
<!-- Other elements -->
</table>
</form>
요소는 표 내부에서 시작되지만 표 요소 외부에서 닫힙니다. 이것은 HTML 사양에서 허용되며 HTML Agility Pack은이를 처리해야합니다.
그냥 배열로 가져 가라.
HtmlNodeCollection resultCollection = doc.DocumentNode.SelectNodes("//*[@type='text']");