2010-03-12 3 views
0

J'ai un balisage qui contient certaines balises d'image HTML avec la classe en vedette. Ce dont j'ai besoin est de trouver toutes ces images, ajouter une balise d'ancrage autour de l'image, définir l'attribut href de l'ancre à la valeur src des images (le chemin de l'image), et enfin remplacer la valeur src des images par une nouvelle valeur une méthode qui retournera cette valeur).Trouver des images qui ont un certain nom de classe HTML

<p>Some text here <img src="/my/path/image.png" alt="image description" class="featured" />. Some more text and another image that should not be modified <img src="/my/path/image2.png" alt="image description" /></p> 

Devrait devenir. Ne pas utiliser RegEx pour analyser le code HTML.

<p>Some text here <a href="/my/path/image.png"><img src="/new/path/from/method.png" alt="image description" class="featured" /></a>. Some more text and another image that should not be modified <img src="/my/path/image2.png" alt="image description" /></p> 
+0

Cela peut être fait avec jQuery sur le client. Avez-vous juste besoin d'un script unique de style find and replace côté serveur ou seriez-vous capable de l'implémenter sur vos clients avec jQuery? – Codesleuth

+0

Besoin de faire cela sur le serveur afin qu'il fonctionne pour ceux qui n'ont pas JavaScript ou n'ont pas activé JavaScript. –

Répondre

0

Voir this classique SO répondre pour les raisons. Utilisez à la place le HTML Agility Pack - vous pouvez utiliser XPath pour interroger votre code HTML.

+0

Merci! Se penchera sur HTML Agility Pack –

0

Terminé avec ce code.

using System; 

en utilisant System.Reflection; en utilisant HtmlAgilityPack; en utilisant log4net;

espace de noms

Company.Web.Util {public static class HTMLParser { private static readonly ILog _log = LogManager.GetLogger (MethodBase.GetCurrentMethod() DeclaringType.); private static HtmlDocument _htmlDocument;

public static string Parse(string input) 
    { 
     _htmlDocument = new HtmlDocument(); 

     _htmlDocument.LoadHtml(input); 
     ParseNode(_htmlDocument.DocumentNode); 

     return _htmlDocument.DocumentNode.WriteTo().Trim(); 
    } 

    private static void ParseChildren(HtmlNode parentNode) 
    { 
     for (int i = parentNode.ChildNodes.Count - 1; i >= 0; i--) 
     { 
      ParseNode(parentNode.ChildNodes[i]); 
     } 
    } 

    private static void ParseNode(HtmlNode node) 
    { 
     if (node.NodeType == HtmlNodeType.Element) 
     { 
      if (node.Name == "img" && node.HasAttributes) 
      { 
       for (int i = node.Attributes.Count - 1; i >= 0; i--) 
       { 
        HtmlAttribute currentAttribute = node.Attributes[i]; 
        if ("class" == currentAttribute.Name && currentAttribute.Value.ToLower().Contains("featured")) 
        { 
         try 
         { 
          string originaleImagePath = node.Attributes["src"].Value; 

          string imageThumbnailPath = GetImageThumbnail(originaleImagePath); 

          var anchorNode = HtmlNode.CreateNode("<a>"); 
          var imageNode = HtmlNode.CreateNode("<img>"); 

          imageNode.SetAttributeValue("alt", node.Attributes["alt"].Value); 
          imageNode.SetAttributeValue("src", imageThumbnailPath); 

          anchorNode.SetAttributeValue("href", originaleImagePath); 

          anchorNode.AppendChild(imageNode); 
          node.ParentNode.InsertBefore(anchorNode, node); 

          node.ParentNode.RemoveChild(node); 
         } 
         catch (Exception exception) 
         { 
          if (_log.IsDebugEnabled) 
          { 
           _log.WarnFormat("Some message: {0}", exception); 
          } 
         } 
        } 
       } 
      } 
     } 

     if (node.HasChildNodes) 
     { 
      ParseChildren(node); 
     } 
    } 
} 

}

Questions connexes