【问题标题】:Converting XElement to HTML string将 XElement 转换为 HTML 字符串
【发布时间】:2011-03-09 11:17:48
【问题描述】:

我正在使用 Xml 和 Linq 对 XHTML 文档执行 XML 操作。

当将其转换回字符串以输出到浏览器时,它会在创建 XElement 时以原始提供的形式呈现脚本标签 <script />.

这会阻止市场上大多数浏览器正确处理它。

我想以这样的方式执行 XElement 到 String 的转换,它输出像这样的脚本标记<script></script>

有人可以帮助我吗?提前致谢。 :)

第一次编辑 提供更多信息,数据来自 MSSQL 2008R2 数据库中的 xml 字段。 它从 xml 字段加载为 <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js" />

第二次修改 工作样本

using System;
using System.Linq;
using System.Xml.Linq;

namespace Test1
{
    class Test1
    {
        static void Main(string[] args)
        {
            XElement element = XElement.Parse("<div><script /><script>Test</script></div>");
            var EmptySet = (from e in element.DescendantsAndSelf()
                           where e.IsEmpty
                           select e);
            foreach(XElement e in EmptySet)
            {
                e.Value = String.Empty;
            }
            Console.WriteLine(element.ToString(SaveOptions.None));
        }
    }
}

及其结果

<div>
  <script></script>
  <script>Test</script>
</div>

【问题讨论】:

    标签: html xml linq scripting xelement


    【解决方案1】:

    您是否尝试过使用SaveOptions.DisableFormatting

    请注意,我实际上无法重现该问题...您正在执行哪些 XML 操作?您是自己创建script 元素吗?这工作正常:

    using System;
    using System.Xml.Linq;
    
    class Test
    {
        static void Main()
        {
            XElement element = XElement.Parse("<script></script>");
            // Both of these write <script></script>
            Console.WriteLine(element.ToString(SaveOptions.None));
            Console.WriteLine(element.ToString(SaveOptions.DisableFormatting));
        }
    }
    

    XDocument.SaveXElement.Save 具有相同的选项。)

    编辑:要将没有子节点的元素更改为具有单个空文本节点的元素,您只需将element.Value 设置为“”。例如:

    XElement element = XElement.Parse("<script />");
    Console.WriteLine(element.ToString()); // Prints <script />
    element.Value = "";
    Console.WriteLine(element.ToString()); // Prints <script></script>
    

    【讨论】:

    • 不幸的是,xml 来自数据库,因此它作为 来自数据库当我把它放在 Parse 示例中时,它输出
    • @Michael:所以这并不是将脚本标签转换&lt;script /&gt;——它忠实地格式化了数据库中的XML。
    • 谢谢您,我已将您标记为答案。作为一个快速的问题,如果脚本标记是深层后代 XElement 而不是父级,那么根据您的示例搜索 XElement 以将所有空元素更改为具有空字符串的最简单方法是什么。
    • @Michael:doc.Descendants().Where(x =&gt; x.Value == "") 这样的东西应该可以工作。您可能希望在修改元素之前具体化查询(将其转换为列表)。请注意,就我所见,即使没有孩子,获取 Value 属性也会返回 "" 而不是 null。
    • 感谢乔恩的帮助。 :) 我发现对 IsEmpty 的测试返回它是否为空,所以我已经对其进行了更正,并让它按照我想要的方式工作。
    【解决方案2】:

    使用

    XElement.Save(XmlWriter writer)
    

    作为 XmlWriter 的输出,您使用 StringWriter 是快速可靠地获得所需内容的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      相关资源
      最近更新 更多