反转义特殊字符我有以下代码如何在C#
XElement element = new XElement("test", "a&b");
其中
element.LastNode
包含值"a&b"
。
我想成为它"a&b"
。
我该如何更换?
反转义特殊字符我有以下代码如何在C#
XElement element = new XElement("test", "a&b");
其中
element.LastNode
包含值"a&b"
。
我想成为它"a&b"
。
我该如何更换?
尝试以下:
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(" ", " ");
htmlstring = htmlstring.Replace("&", "&");
return htmlstring;
}
使用HTML敏捷包代替http://htmlagilitypack.codeplex.com/ – Jodrell 2014-10-09 10:34:10
的&是保留字符所以它将永诺进行编码。所以,你必须解码:
这是一个选项: HttpUtility.HtmlDecode Method (String)
用法:
string decoded = HttpUtility.HtmlDecode("a&b");
// returns "a&b"
这个工程,但我不能分配这个字符串值到Xelement.Lastnode – user2392525 2014-10-09 09:56:58
当然你可以,但它会被自动编码 – 2014-10-09 09:59:09
你可以只是阅读'element.Value',你应该小心HTML解码XML,它工作正常'&'但不是所有的角色都能以这两种标准以相同的方式逃脱。 – Jodrell 2014-10-09 10:37:22
稍等片刻,
<测试>一& b < /测试>
是无效的XML。你不能让XML看起来像这样。这是clarified by the XML standard。
&
具有特殊含义,它表示可能会失效的转义字符。 '&'
字符在XML中编码为&
。
为什么它的价值,这是无效的HTML出于同样的原因。
<!DOCTYPE HTML> < HTML> <体>一& 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
。
如果你想使一个文件,看起来像
<测试>一& b < /测试>
你可以,但它不是XML或HTML工具工作使用HTML或XML不会有意帮助你。你将拥有自己的读者,作家和解析者。
你正在运行哪种语言? – 2014-10-09 09:30:17
我正在使用c#.net – user2392525 2014-10-09 09:31:45
我试图做XElement element = new XElement(“test”,HttpUtility.HtmlDecode(“a &b")); – user2392525 2014-10-09 09:36:38