简体   繁体   中英

Decoding from Base64 in C#

I created XML Document and saved this document as

  XmlDocument xmlDoc = new XmlDocument();
  XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
  xmlDoc.AppendChild(dec);
  XmlTextWriter writer = new XmlTextWriter(fullPath,Encoding.UTF8);
  writer.Formatting = Formatting.Indented;
  xMLDoc.Save(writer);
  writer.Flush();

And then I have encoded this document using Base64 Encoder

The Decoder could not parse XML file. I created the decoder myself and got this result

 ?<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<ClinicalDocument 
 xmlns=\"urn:hl7-org:v3\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
classCode=\"DOCCLIN\" moodCode=\"EVN\" schemaLocation=\"urn:hl7-org:v3
CDA.xsd\">\r\n  <typeId extension=\"POCD_HD000040\" root=\"2.16.840.1.113883.1.3
\" />\r\n

Please help me to resolve the issue. How I have to save the XML file to avoid the issues? Or How I have to encode to Base 64 to resolve the issue? I am using base64 encoder to encode xml file. I am requesting document. it is required to use base64 encoder. I decoded myself to check where is the problem. The decoder is Java . They can not parse the xml file I believe because ?< in front of the document.

It depends on how you're encoding it, but you should use UTF-8 since the document is declared as such. Here are examples for encoding and decoding:

See Jon Skeet's answer here:
C# base64 encoding/decoding with serialization of objects issue

To encode:

public string EncodeStringToBase64(string stringToEncode)
{
    return Convert.ToBase64String(Encoding.UTF8.GetBytes(stringToEncode));
}

To decode:

public string DecodeStringFromBase64(string stringToDecode)
{       
    return Encoding.UTF8.GetString(Convert.FromBase64String(stringToDecode));
}

One other option - could be BOM in default Utf-8 stream created by new XmlTextWriter(fullPath,Encoding.UTF8);

Consider using second constructor for UTF8 - http://msdn.microsoft.com/en-us/library/s064f8w2.aspx that does not insert BOM into the stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM