2017-11-22 1 views
-2

ich in einer schwierigen Situation stecken bin, habe ich diese Zeichenfolge in C# mit HTML-Tags:Finden und fehlenden Stil hinzufügen Attribute zu einer HTML-Zeichenfolge in C#

String strHTML = "<span style="font-size: 10px;">Hi This is just a section of html text.</span><span style="font-family: 'Verdana'; font-size: 10px;">Please help</span><span>me add style attributes to span tags.Thank You</span>";

Wie Sie sehen können, gibt es zwei span-Tags ohne "font-family: 'Verdana';". Ich brauche etwas, das mir helfen kann, font-family zu diesen beiden span-Tags hinzufügen, damit das gewünschte Ergebnis in etwa so sein würde:

<span style="font-size: 10px;font-family: 'Verdana';">Hi This is just an example of html text.</span><span style="font-family: 'Verdana'; font-size: 10px;">Please help<span style="font-family: 'Verdana';">me add style attributes to span tags.Thank You</span>

Ich weiß, dass ich einfach eine andere Span-Tag am Anfang hinzufügen von der Schnur, aber das ist etwas, was ich nicht tun möchte. Jede Hilfe würde sehr geschätzt werden.

Bearbeitungen: Ich habe versucht, mit Regex.Replace-Methode für Stunden. Aber ich konnte einfach nicht die richtige Ausgabe bekommen.

+0

Ist der HTML-Code garantiert gültig? (ausgeglichen öffnen/schließen Tags, Kodierung, etc.) – JuanR

+0

http://idownvotedbecau.se/noattempt/ – Sefe

+0

ja .. das ist nur ein Beispiel html Ich habe für Ihre Referenz hinzugefügt. – DevSa

Antwort

1

Eine Möglichkeit, es ohne Regex zu tun wäre, die HtmlAgilityPack Bibliothek zu verwenden und eine rekursive Funktion:

public void SetFonts() 
{ 
    string strHtml = "<span style=\"font-size: 10px; \">Hi This is just a section of html text.</span><span style=\"font-family: 'Verdana'; font-size: 10px; \">Please help</span><span>me add style attributes to span tags.Thank You</span>"; 
    HtmlDocument document = new HtmlDocument(); 
    document.LoadHtml(strHtml); 
    SetFonts(document.DocumentNode); 
    document.Save(Console.Out); 
} 


public void SetFonts(HtmlNode node) 
{ 
    foreach (var item in node.Elements("span")) 
    { 
     var style = item.GetAttributeValue("style", null); 
     if (style != null) 
     { 
      if (!style.Contains("font-family")) 
      { 
       var newValue = style + "font-family: 'Verdana';"; 
       item.SetAttributeValue("style", newValue); 
      } 
     } 
     SetFonts(item); 
    }    
} 

Das Ergebnis:

<span style="font-size: 10px; font-family: 'Verdana';">Hi This is just a section of html text.</span><span style="font-family: 'Verdana'; font-size: 10px; ">Please help</span><span>me add style attributes to span tags.Thank You</span> 

Hinweis: Das wird nicht span-Tags mit keinem Ziel Stil überhaupt. Sie können es ändern, um dies zu tun, wenn Sie es brauchen.

Sie können die HtmlAgilityPack-Bibliothek von NuGet herunterladen.

+0

Ehrfürchtig. Vielen Dank Juan. Genau das, was ich brauchte. Danke nochmal. :) – DevSa

Verwandte Themen