如何停止XDocument.Save编写转义字符 [英] How to stop XDocument.Save writing escape chars

查看:41
本文介绍了如何停止XDocument.Save编写转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 SQL db 中的 varchar列中读取XML数据,并将其读入属于的sql XElement 的linq中> XDocument .

I'm reading XML data from a varchar column in a SQL db, into a linq to sql XElement belonging to an XDocument.

当我执行 XDocument.Save 方法时,XML被写入文件,但包含转义字符.例如,将>" 更改为& gt" .

When I execute the XDocument.Save method, the XML is written to file but includes the escape characters. For example, ">" is changed to "&gt".

有防止这种情况的简便方法吗?

Is there an easy way to prevent this?

推荐答案

首先,似乎没有理由阻止它.就像提到的肯尼一样,除非特殊字符经过XML编码,否则解析器将无法解析生成的XML(因为<"或>"字符对该解析器意义重大).其次,当您的解析器解码XML(例如,您调用XElement.Value)时,所有特殊字符都将被转换回原来的状态.最后,如果您想保留原始字符串(例如,出于XML解析之外的目的),则可以使用CDATA,在Linq2XML的情况下,该数据由XCData类表示.

First, there seems to be no reason to prevent it. Like kenny mentioned, unless special characters are XML encoded, no parser would be able to parse produced XML (because '<' or '>' characters means a lot for that parser). Second, when your parser decodes XML (e.g. you call XElement.Value), all special characters will be converted back to what they originally were. Finally, if you want to keep the original string (e.g. for purposes other than XML parsing), you can use CDATA, which in case of Linq2XML is represented by XCData class.

编辑:正如罗伯指出的那样,我可能弄错了.如果要进行保存,则将现有XML添加到文档中,而不会出现特殊字符,请使用以下代码:

EDIT: As Rob pointed out, I might have gotten it wrong. If the point is to save add existing XML to a document, without special characters appear, use the following code:

XDocument document = new XDocument();
var xmlFromDb = "<xml>content</xml>";
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlFromDb))) 
{
     using (var reader = XmlReader.Create(stream)) {
          reader.MoveToContent();
          document.Add(XElement.ReadFrom(reader));
     }
}

这篇关于如何停止XDocument.Save编写转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆