Html Agility Pack - Get html fragment from an html document

亡梦爱人 提交于 2019-12-11 02:09:33

问题


Using the html agility pack; how would I extract an html "fragment" from a full html document? For my purposes, an html "fragment" is defined as all content inside of the <body> tags.

For example:

Sample Input:

<html>
   <head>
     <title>blah</title>
   </head>
   <body>
    <p>My content</p>
   </body>
</html>

Desired Output:

<p>My content</p>

Ideally, I'd like to return the content unaltered if it didn't contain an <html> or <body> element (eg. assume that I was passed a fragment in the first place if it wasn't a full html document)

Can anyone point me in the right direction?


回答1:


I think you need to do it in pieces.

you can do selectnodes of document for body or html as follows

doc.DocumentNode.SelectSingleNode("//body") // returns body with entire contents :)

then you can check for null values for criteria and if that is provided, you can take the string as it is.

Hope it helps :)




回答2:


The following will work:

public string GetFragment(HtmlDocument document)
{
   return doc.DocumentNode.SelectSingleNode("//body") == null ? doc.DocumentNode.InnerHtml : doc.DocumentNode.SelectSingleNode("//body").InnerHtml;
}


来源:https://stackoverflow.com/questions/4348520/html-agility-pack-get-html-fragment-from-an-html-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!