Html Agility Pack - 从html文档中获取html片段

Dan*_*anP 2 html c# html-agility-pack

使用html敏捷包; 如何从完整的HTML文档中提取html"片段"?为了我的目的,html"片段"被定义为<body>标签内的所有内容.

例如:

样本输入:

<html>
   <head>
     <title>blah</title>
   </head>
   <body>
    <p>My content</p>
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)

期望的输出:

<p>My content</p>
Run Code Online (Sandbox Code Playgroud)

理想情况下,如果内容不包含<html>或者<body>元素,我想保留未更改的内容(例如,如果它不是一个完整的html文档,则假设我首先传递了一个片段)

谁能指出我正确的方向?

Man*_*iya 6

我想你需要分成几部分.

您可以按如下方式为body或html执行文档的选择节点

doc.DocumentNode.SelectSingleNode("//body") // returns body with entire contents :)
Run Code Online (Sandbox Code Playgroud)

然后你可以检查标准的空值,如果提供了,你可以按原样取字符串.

希望能帮助到你 :)


Osc*_*ros 5

以下将有效:

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