How to stop XDocument.Save writing escape chars

前端 未结 1 918
暖寄归人
暖寄归人 2021-01-22 10:31

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

When I

相关标签:
1条回答
  • 2021-01-22 10:53

    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.

    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));
         }
    }
    
    0 讨论(0)
提交回复
热议问题