【问题标题】:How to unescape special characters in c#如何在c#中取消转义特殊字符
【发布时间】:2014-10-09 09:29:07
【问题描述】:

我有以下代码

XElement element = new XElement("test", "a&b");

在哪里

element.LastNode 包含值"a&b"

我想成为它"a&b"

如何替换这个?

【问题讨论】:

  • 您使用哪种语言?
  • 我试着做 XElement element = new XElement("test", HttpUtility.HtmlDecode("a&b"));
  • & 不是 XML 中的有效字符,因为它引入了实体代码。 &在 XML 中用于 &。
  • 但是如果我想替换我该怎么做
  • 你不能!否则,您的 XML 将不再是有效的 XML。

标签: c# xelement


【解决方案1】:

等一下,

a&b

不是有效的 XML。您不能制作看起来像这样的 XML。这是clarified by the XML standard

& 有特殊含义,它表示转义字符,否则可能无效。 '&' 字符在 XML 中编码为 &


出于同样的原因,这是无效的 HTML。

a&b

如果我写代码,

const string Value = "a&b";
var element = new XElement("test", Value);
Debug.Assert(
    string.CompareOrdinal(Value, element.Value) == 0,
    "XElement is mad");

它运行时不会出错,XElement 根据需要对 XML 进行编码和解码。

要取消转义或解码 XML 元素,您只需阅读 XElement.Value

如果你想制作一个看起来像这样的文档

a&b

你可以,但它不是 XML 或 HTML,处理 HTML 或 XML 的工具不会有意帮助你。您将拥有自己的阅读器、编写器和解析器。

【讨论】:

    【解决方案2】:

    & 是一个保留字符,所以它总是被编码。所以你必须解码:

    这是一个选项: HttpUtility.HtmlDecode Method (String)

    用法:

    string decoded = HttpUtility.HtmlDecode("a&b");
    // returns "a&b"
    

    【讨论】:

    • 这可行,但我无法将此字符串值分配给 Xelement.Lastnode
    • 当然可以。但会自动编码。
    • 你可以阅读element.Value,你应该小心HTML解码XML。它适用于&,但并非所有字符都以相同的方式按照两种标准进行转义。
    • @user2392525 添加 a&b 而不对其进行编码会导致 xml 语法不正确。 <test>a&b</test> 有语法错误。 <test>a&b</test> 是正确的。它只需要你解码值
    【解决方案3】:

    尝试以下操作:

    public static string GetTextFromHTML(String htmlstring)
        {
            // replace all tags with spaces...
           htmlstring= Regex.Replacehtmlstring)@"<(.|\n)*?>", " ");
    
           // .. then eliminate all double spaces
           while (htmlstring).Contains("  "))
           {
               htmlstring= htmlstring.Replace("  ", " ");
            }
    
           // clear out non-breaking spaces and & character code
           htmlstring = htmlstring.Replace("&nbsp;", " ");
           htmlstring = htmlstring.Replace("&amp;", "&");
    
           return htmlstring;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2013-06-09
      • 2017-04-02
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多