2011-02-18 4 views
3

J'ai un éditeur WYSIWYG qui construit du contenu HTML. Les balises ne sont pas toujours construites en tant que xml valide, et j'en ai besoin pour être valide xml. Quelqu'un at-il un tel script? Comment ferais-je cela?Script pour convertir le balisage html en XML valide

+0

Quelle langue côté serveur? – alex

+0

Avez-vous une chance de réparer l'éditeur? –

+0

@ John Saunders, oui. –

Répondre

4

Je ne suis pas sûr de ce que la langue que vous utilisez sur le serveur, mais vous pouvez regarder dans le Html Agility Pack si vous utilisez .NET

+0

J'ai trouvé que Html Agility Pack a quelques bugs. Dans certains cas, produit du XML non valide. – Muxa

1

Il y a un certain nombre d'outils tels que la TagSoup de John Cowan qui font un bon travail de conversion HTML en XML.

2

Il pourrait être utile d'avoir un regard sur cette version .NET de HTML Tidy: Tidy.NET

1

Microsoft a publié un exemple de code: SgmlReader. Il vous permet de lire (entre autres formats) bien rangé html.

j'ai écrit une petite méthode utilitaire qui convertit une chaîne Html à une chaîne xml:

/// <summary> 
/// Converts a string from potential dirty HTML to valid XML 
/// </summary> 
/// <param name="input">The string to convert</param> 
/// <returns>A valid XML fragment that contains the cleaned HTML</returns> 
/// <remarks>This methods only format the html to an xml compatible parser. 
/// The method does not clean dangerous tags from the source string</remarks> 
public static string HtmlToXHtml(string input) 
{ 
    using (var sr = new StringReader(input)) 
    { 
     var hr = new SgmlReader(sr); 
        hr.InputStream = sr; 
        hr.DocType = "HTML"; 
     var output = new StringBuilder(); 
     var hw = new XmlTextWriter(new StringWriter(output)); 

     hr.Read(); 
     while (!hr.EOF) 
     { 
      hw.WriteNode(hr, true); 
     } 


     return output.ToString(); 
    } 
} 

Vous pouvez « simplement » mettre à jour l'entrée d'utilisateur après la publication. Dans des scénarios plus complexes (pour passer du mode source wysiwyg au mode source HTML), vous pouvez avoir besoin d'un bit Ajax pour convertir la chaîne html en xhtml derrière le rideau, avant d'afficher la source html dans la zone de texte.

Questions connexes