Reputation: 16310
I need to get a nested div with an html document, for example:
<div id="maindiv>
<div id='firstdiv'>
</div>
<div id="otherid">
<div id="anotherdiv"><div id="divid"></div>
</div>
</div>
I need to get the content of anotherdiv
. I don't know how deep both maindiv
might be within the main document and how deep anotherdiv
might be within maindiv
.
Currently I'm doing:
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(content);
var main = doc.GetElementbyId("maindiv").InnerHtml;
doc.LoadHtml(main);
var another = doc.GetElementbyId("anotherdiv");
This works fine. However is there a better way to get the required div by using XPath?
Upvotes: 3
Views: 1671
Reputation: 76
if you want to extract child using x path you use "/" but you can also can extract grand child by "/*/" or use "//" if you dont know how deep is the element.
to extract element by id use [@id='<id_you_are_looking_for']
(same way to extract by class)
so if you don't know how "deep" is your div just use
//div[@id='anotherdiv']
or even
//*[@id='anotherdiv']
to extract any element with selected id.
id should be unique so it should be enough but if you want to make sure that another div is in main div you can use
//div[@id='maindiv']//div[@id='anotherdiv]
Upvotes: 5