c# - C#中如何对特殊字符进行转义

标签 c# xelement

我有以下代码

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

在哪里

element.LastNode 包含值 "a&b"

我想成为它 "a&b"

我该如何替换它?

最佳答案

等一下

<test>a&b</test>

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

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


就其值(value)而言,出于同样的原因,这是无效的 HTML。

<!DOCTYPE html> <html> <body> a&b </body> </html>


如果我写代码,

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

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

<test>a&b</test>

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

关于c# - C#中如何对特殊字符进行转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26274933/

相关文章:

c# - ASP NET MVC C# - .Model 是一个属性,但它像一个类型一样使用

c# - ServiceStack CORS - 仅在 IE 中不响应 OPTIONS 请求

c# - 在 C# 中从 XML 中删除元素

c# - 创建空白 XML 文件,然后附加到它

c# - 省略 XML 声明?

.net - 给定 XElement,如何在给定 XPath 的情况下检索对另一个相关 XElement/Xattribute 的引用?

c# - XElement 的子元素

c# - 使用 Span<T> 替代 Substring

c# - 如何以编程方式找出 JRE 网络设置?

C# 无法访问该文件,因为它已被其他进程使用