0

私はメールを送信するCLRプロシージャを実行しており、htmlを文字列に構成しました。いくつかの動的な値をバインドした後、メールを送信することができました。

しかし、今問題は、HTMLを含む文字列を取得しているので、最初に見つけてから<table>その幅を変更したいと思います。それ。[幅が広いため、テンプレートが邪魔です]。これはメールの本文です。

 string StrHtml =" <table cellspacing='1' cellpadding='10' border='0'
style='width:880px'></table>"

変更したいstyle='width:880px' to style='width:550px'

私はこのコードをクラスライブラリでのみ実行しています。これを行うための最良の方法は何ですか?

私のコードは:

string ImgPath = string.Empty;
ImgPath = Convert.ToString(ds.Tables[0].Rows[i]["GroupMessage"]);
string pattern = string.Empty;
pattern = System.Text.RegularExpressions.Regex.(ImgPath, "(<table.*?>.*</table>", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Groups[1].Value;  

MailMessage message = new MailMessage();
message.AlternateViews.Add(htmlMail);
message.Body = ImgPath ; //
message.IsBodyHtml = true;
//Other mail sending code here.....
4

4 に答える 4

2

HtmlAgilityPackと次のようなものを使用できます。

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(StrHtml);

var tableNode = ( from node in htmlDoc.DocumentNode.Descendants()
                 where node.Name == "table"
                 select node ).FirstOrDefault();

if ( tableNode != null ) {
    tableNode.Attributes["style"].Value = 
        tableNode.Attributes["style"].Value.Replace("880px", "550px");
}
于 2012-11-05T10:35:41.750 に答える
0

あなたはこれを行うことができますXDocument

    using (var reader = new StringReader(StrHtml))
    {
       var doc = XDocument.Load(reader);
       var table = doc.Descendants("table").FirstOrDefault();
       if (table != null)
       {
           var style = table.Attribute("Style");
           if (style != null)
               style.Value = "width:550px";
       }
    }
于 2012-11-05T10:37:35.473 に答える
0

これだけで何が悪い?

StrHtml = StrHtml.Replace("880px","550px");

それとも単なる例でしたか?申し訳ありませんが、明確ではありません。

編集:

正規表現 (System.Text.RegularExpressions; を使用):

StrHtml = Regex.Replace(StrHtml, "width:[\d]*px", "width:550px");

"width:(numbers)px" テキストが存在する必要がある (および width は正規表現と同じ小文字でなければならない) か、例外が発生することに注意してください。しかし、それを a で囲むだけでtry{StrHtml = Regex.Replace(StrHtml, "width:[\d]*px", "width:550px");}catch{}問題ありません

最終最終編集:

table タグのみのスタイル幅を取得したい場合は、次のように収集します。

try{
StrHtml = Regex.Replace(StrHtml, @"(<table[\s\S]*)(width:[\d]*px)(.*?>)", @"$1width:550px$3");
}
catch{}
于 2012-11-05T10:38:20.290 に答える
0

以下の形式で html 文字列を取得しており、常に変化している style="width: 880px" の属性値のみを取得したい [これは、スタイルタグで幅が言及されている場合にのみ機能します。それが私の場合です。]

ImgPath ==>

 <table border="0" cellpadding="10" cellspacing="1" style="width: 880px">
    // some other code goes here
    </html>

回答 ==> クラスで正規表現を使用しました [そのクラスから DLL ファイルを作成したい]

string StrStyTag = string.Empty;
StrStyTag = System.Text.RegularExpressions.Regex.Match(ImgPath, "<table.+?style=(.+?)>", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Groups[1].Value;

==> "width: 880px" として値を取得しているため、いくつかの文字列操作を行った後、550px を修正するために 880px を作成します。

私がそれを解決するのを手伝ってくれたすべての人に感謝します。

于 2012-11-07T10:26:24.230 に答える