如何在C#中使用匹配和替换字符串部分的函数

时间:2012-10-05 03:20:53

标签: c#

我有网页HTML代码,如下所示:

<html>
<div class="code" id="one">
<pre>
      int i = 1;
      int j = 2;
</pre>
</div>
<h1>Sample heading</h1>
<div class="code" id="two">
<pre>
      int i = 1;
      int j = 2;
</pre>
</div>

代码在C#字符串中,我需要做的是找到一些方法用这样的东西替换<pre>区域:

<table>
<tr><td>1</td><td><code>   int i = 1</code></td></tr>
<tr><td>2</td><td><code>   int j = 2</code></td></tr>
</table>

如何获取原始字符串并创建一个由原始数据组成的新字符串,但有一些函数可以转换应用于<pre>文本区域的<pre>文本?

1 个答案:

答案 0 :(得分:0)

如果我是你,我会使用某种形式的XML解析器来定位<pre>元素。

    XDocument loDoc = XDocument.Parse(lcHTML);

    foreach (XElement loElement in loDoc.Descendants("pre"))
    {
        //-- Modify the html to your heart's content.
        //-- You can split the html on newline character, prefix each line with your table stuff along with the line index. Then write the XML back out.
    }