如何防止 XElement 解码字符实体引用
我有一个包含撇号的 XML 字符串。我将撇号替换为其等效的 &将修改后的字符串解析为 XElement。然而,XElement 将 ' 后面变成了撇号。
如何强制 XElement.Parse 保留编码字符串?
string originalXML = @"<Description><data>Mark's Data</data></Description>"; //for illustration purposes only
string encodedApostrophe = originalXML.Replace("'", "'");
XElement xe = XElement.Parse(encodedApostrophe);
I have an XML string that contains an apostrophe. I replace the apostrophe with its equivalent & parse the revised string into an XElement. The XElement, however, is turning the ' back into an apostrophe.
How do I force XElement.Parse to preserve the encoded string?
string originalXML = @"<Description><data>Mark's Data</data></Description>"; //for illustration purposes only
string encodedApostrophe = originalXML.Replace("'", "'");
XElement xe = XElement.Parse(encodedApostrophe);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是正确的行为。在允许
'
的地方,其作用与'
、'
或&# x27;
。如果你想在 XML 中包含文字字符串'
,你应该对&
进行编码:或者解析原始 XML 并修改它:
但是这样做似乎真的很奇怪。也许对于您想要解决的问题有更好的解决方案。
此外,这种编码不是“ASCII 等效”,它们被称为字符实体引用。数字是基于字符的 Unicode 代码点。
This is correct behavior. In places where
'
is allowed, it works the same as'
,'
or'
. If you want to include literal string'
in the XML, you should encode the&
:Or parse the original XML and modify that:
But doing this seems really weird. Maybe there is a better solution to the problem you're trying to solve.
Also, this encoding is not “ASCII equivalent”, they are called character entity references. And the numeric ones are based on the Unicode codepoint of the character.