使用特定条件从字符串中获取值

时间:2012-10-05 09:31:31

标签: c# string

我的字符串中有一个html数据,我只需要获取段值​​。下面是一个示例html。

<html>
  <head>
    <title>
       <script>
          <div>
               Some contents
           </div>
          <div>
            <p> This is what i want </p>
            <p> Select all data from p </p>
            <p> Upto this is required </p>
          </div>
         <div>
          Other html elements
         </div>

那么如何使用字符串操作从段落中获取数据。

期望输出

<Div>
  <p> This is what i want    </p>
  <p> Select all data from p </p>
  <p> Upto this is required  </p>
</div>

4 个答案:

答案 0 :(得分:1)

给div一个ID,例如

<div id="test">
<p> This is what i want </p>
<p> Select all data from p </p>
<p> Upto this is required </p>
</div>

然后使用//div[@id='test']/p

解决方案:

//div                    - All div elements
[@id='test']   - With an ID attribute whose value is test
/p    

答案 1 :(得分:0)

我曾使用Html agility Pack这样的事情。然后你可以使用LINQ来获得你想要的东西。

答案 2 :(得分:0)

Xpath是一个明显的答案(如果HTML很好,有一个根等),失败了一些第三方小部件,如chilkat

答案 3 :(得分:0)

如果您使用其他帖子中提到的Html Agility Pack,您可以使用以下命令获取html中的所有段落元素:

HtmlDocument doc = new HtmlDocument();
doc.Load("your html string");
var pNodes = doc.DocumentNode.SelectNodes("//div[@id='id of the div']/p")

由于您使用的是.net Framework 2.0,因此您需要旧版本的Agility Pack,可在此处找到:HTML Agility Pack

如果您只想要段落中的文字,可以使用

var pNodes = doc.DocumentNode.SelectNodes("//div[@id='id of the div']/p/text()")