i have xml what i get as byte array, whats the best way to get the xml string out of it? I was tryng to use xmltextreader and memorystream but with no success..
-
1Where do you get the byte array from? Do you know the encoding used?R. Martinho Fernandes– R. Martinho Fernandes2011-04-07 13:51:19 +00:00Commented Apr 7, 2011 at 13:51
-
XML containes base64 encoded data..hs2d– hs2d2011-04-07 13:54:58 +00:00Commented Apr 7, 2011 at 13:54
-
I meant the character encoding of the XML document.R. Martinho Fernandes– R. Martinho Fernandes2011-04-07 13:56:04 +00:00Commented Apr 7, 2011 at 13:56
Add a comment
|
4 Answers
XmlDocument doc = new XmlDocument();
string xml = Encoding.UTF8.GetString(buffer);
doc.LoadXml(xml);
OR
XmlDocument doc = new XmlDocument();
MemoryStream ms = new MemoryStream(buffer);
doc.Load(ms);
This assumes your data has UTF8 encoding which is the usual for XML. Also buffer here is the byte array.
2 Comments
firefox1986
Good answer, although the MemoryStream is IDisposable so don't forget to wrap it in a using block! :)
bkwdesign
because of a byte order mark (BOM) I found this overload more useful (thanks Jon Skeet)
MemoryStream ms = new MemoryStream(buffer, true);Assuming your xml is in the default 'UTF8' encoding., you could do something like this;
string xml = System.Text.UTF8Encoding.UTF8.GetString(bytes);
System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument().LoadXml(xml);
Or this;
XmlDocument doc = new XmlDocument();
using (MemoryStream ms = new MemoryStream(buffer))
{
doc.Load(ms);
}
Comments
Based on the Encoding, you can do
string xmlString = System.Text.UTF8Encoding.UTF8.GetString(bytes);
and use the string
XmlTextReader reader = new XmlTextReader(new StringReader(xmlString));
1 Comment
R. Martinho Fernandes
Ooops... GetBytes takes a string and gives an array of bytes. GetString takes an array of bytes and gives a string. FTFY.
Take a look at the System.Text.Encoding.UTF8 class. It should let you convert youre byte array into a UTF8 string.
2 Comments
NKCSS
See XML Encoding Defaults page here. UTF8 is the correct assumption is most cases.
R. Martinho Fernandes
Still, I think you should have a note about it on your answer.