【问题标题】:Script for converting html markup to valid XML用于将 html 标记转换为有效 XML 的脚本
【发布时间】:2011-06-29 13:54:59
【问题描述】:

我有一个构建 HTML 内容的 WYSIWYG 编辑器。标签并不总是构建为有效的 xml,我需要它是有效的 xml。有人有这样的剧本吗?我该怎么做?

【问题讨论】:

  • 你能修复编辑器吗?

标签: .net xml xhtml html-parsing wysiwyg


【解决方案1】:

微软发布了一个代码示例:SgmlReader。它允许您阅读(以及其他格式)整洁的 html。

我写了一个将 Html 字符串转换为 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();
    }
}

您可以在回发后“简单地”更新用户输入。 在更复杂的场景中(必须在所见即所得和 Html 源模式之间切换),在 textarea 中显示 html 源之前,您可能需要一些 Ajax 将 html 字符串转换为幕后的 xhtml。

【讨论】:

    【解决方案2】:

    可能值得看看这个 .NET 版本的 HTML Tidy:Tidy.NET

    【讨论】:

      【解决方案3】:

      有许多工具,例如 John Cowan 的 TagSoup,可以很好地将 HTML 转换为 XML。

      【讨论】:

        【解决方案4】:

        我不确定您在服务器上使用的是什么语言,但如果您使用 .NET,您可能需要查看 Html Agility Pack

        【讨论】:

        • 我发现 Html Agility Pack 有一些错误。在某些情况下会产生无效的 XML。
        猜你喜欢
        • 2012-06-07
        • 2016-02-29
        • 2017-05-01
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多