c# create xml from byte array - c#

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..

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.

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);
}

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));

Take a look at the System.Text.Encoding.UTF8 class. It should let you convert youre byte array into a UTF8 string.

Related

XML Deserialization encoding issue

I already searched a lot and unable to find a solution and unable to determine the correct approach
I am serializing an object to xml string and deserializing it back to an object using c#. XML string after serialization adds a leading ?. When I dezerialize it back to the object I am getting an error There is an error in XML document (1, 1)
?<?xml version="1.0" encoding="utf-16"?>
Serialization code:
string xmlString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("abc", "http://example.com/abc/");
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream,Encoding.Unicode);
xs.Serialize(xmlTextWriter, obj, ns);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlString = ConvertByteArrayToString(memoryStream.ToArray());
ConvertByteArrayToString:
UnicodeEncoding encoding = new UnicodeEncoding();
string constructedString = encoding.GetString(characters);
Deserialization Code:
XmlSerializer ser = new XmlSerializer(typeof(T));
StringReader stringReader = new StringReader(xml);
XmlTextReader xmlReader = new XmlTextReader(stringReader);
object obj = ser.Deserialize(xmlReader);
xmlReader.Close();
stringReader.Close();
return (T)obj;
I would like to know what I am doing wrong with encoding and I need a solution that works for most cases. Thanks
Use following function for serialization and Deserialization
public static string Serialize<T>(T dataToSerialize)
{
try
{
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringwriter, dataToSerialize);
return stringwriter.ToString();
}
catch
{
throw;
}
}
public static T Deserialize<T>(string xmlText)
{
try
{
var stringReader = new System.IO.StringReader(xmlText);
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
catch
{
throw;
}
}
Your serialized XML contains a Unicode byte-order mark in the beginning, and this is where the deserializer fails.
To remove the BOM you need to create a different version of encoding suppressing BOM instead of using default Encoding.Unicode:
new XmlTextWriter(memoryStream, new UnicodeEncoding(false, false))
Here the second false prevents BOM being prepended to the string.

Read xml data file into Windows.Data.Xml.Dom.XMLDocument

How can we read a xml data file into Windows.Data.Xml.Dom.XMlDocument?
The following code is possible only for System.Xml.XmlDocument.
XmlDocument myxml = XmlDocument.Load("abc.xml");
I read the xml file content to a string, and then use LoadXml():
string fileContent;
StorageFile tileTemplateFile =
await StorageFile.GetFileFromApplicationUriAsync(new Uri(#"<path to file>"));
using (StreamReader reader =
new StreamReader(await tileTemplateFile.OpenStreamForReadAsync()))
{
fileContent = await reader.ReadToEndAsync();
}
XmlDocument tileXml = new XmlDocument();
tileXml.LoadXml(fileContent);
I got most of the code from this answer.
You need to do the following.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(<string representation of your xml>);

how to save xmldocument to a stream

I've already written code to parse my xml file with an XmlReader so I don't want to rewrite it. I've now added encryption to the program. I have encrypt() and decrypt() functions which take an xml document and the encryption algorithm. I have a function that uses an xml reader to parse the file but now with the xml document I'm not sure how to create the xmlreader.
The question is how to save my xml document to a stream. I'm sure it's simple but I don't know anything about streams.
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(filep);
Decrypt(doc, key);
Stream tempStream = null;
doc.Save(tempStream); // <--- the problem is here I think
using (XmlReader reader = XmlReader.Create(tempStream))
{
while (reader.Read())
{ parsing code....... } }
You can try with MemoryStream class
XmlDocument xmlDoc = new XmlDocument( );
MemoryStream xmlStream = new MemoryStream( );
xmlDoc.Save( xmlStream );
xmlStream.Flush();//Adjust this if you want read your data
xmlStream.Position = 0;
//Define here your reading
Writing to a file:
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<FTPSessionOptionInfo><HostName>ftp.badboymedia.ca</HostName></FTPSessionOptionInfo>");
using (StreamWriter fs = new StreamWriter("test.xml"))
{
fs.Write(doc.InnerXml);
}
}
I realize this is an old question, but thought it worth adding a method from this nice little blog post. This edges out some less performant methods.
private static XDocument DocumentToXDocumentReader(XmlDocument doc)
{
return XDocument.Load(new XmlNodeReader(doc));
}
try this
XmlDocument document= new XmlDocument( );
string pathTmp = "d:\somepath";
using( FileStream fs = new FileStream( pathTmp, FileMode.CreateNew ))
{
document.Save(pathTmp);
fs.Flush();
}

C# XSLT in memory transformation

I am currently running a live 'in-memory' XSLT transformation using the following code
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.LoadXml(DS.GetXml());
XslCompiledTransform XsltTranformation = new XslCompiledTransform();
XsltTranformation.Load(#"C:\Users\maskew\Desktop\XSLTMapping.xsl");
Stream XmlStream = new MemoryStream();
XmlDoc.Save(XmlStream); //Stream is still blank after this line
XmlReader XmlRdr = XmlReader.Create(XmlStream);
MemoryStream stm = new MemoryStream();
XsltTranformation.Transform(XmlRdr, null, stm);
stm.Position = 1;
StreamReader sr = new StreamReader(stm);
string Output = sr.ReadToEnd();
Output = Output.Substring(2);
XmlDoc.LoadXml(Output);
XmlWriter XmlWrtr = XmlWriter.Create(#"C:\Users\maskew\Desktop\XmlMapping.xml");
XmlDoc.WriteTo(XmlWrtr);
XmlWrtr.Flush();
XmlWrtr.Close();
However, when I move the file from XmlDocument to MemoryStream in line 6 the stream contains nothing when checked and thus stopping the whole program from running.
Does anyone have any idea why this would be occuring?
UPDATED: The stream is containing information now, however the XmlReader object is receiving none of it still.
Try a simplyfying
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(DS.GetXml());
// Create a writer for writing the transformed file.
XmlWriter writer = XmlWriter.Create(#"C:\Users\maskew\Desktop\XmlMapping.xml");
// Create and load the transform with script execution enabled.
XslCompiledTransform transform = new XslCompiledTransform();
XsltSettings settings = new XsltSettings();
settings.EnableScript = true;
transform.Load(#"C:\Users\maskew\Desktop\XSLTMapping.xsl", settings, null);
// Execute the transformation.
transform.Transform(xmlDoc, writer);
Try flushing and resetting the stream:
XmlDoc.Save(XmlStream);
XmlStream.Flush();
XmlStream.Position = 0;
XmlReader XmlRdr = XmlReader.Create(XmlStream);
Stream XmlStream = new MemoryStream();
How there can be something in it ? You are constructing an empty memoryStream...
EDIT :
You should try to clarify it by using the 'using' instruction (http://msdn.microsoft.com/fr-fr/library/yh598w02). Basically, class like StreamReader, MemeryStream, etc.. implement the IDisposable interface. If you wrap them with using, it will dispose the object automatically for you.

How can I remove the BOM from XmlTextWriter using C#?

How do remove the BOM from an XML file that is being created?
I have tried using the new UTF8Encoding(false) method, but it doesn't work. Here is the code I have:
XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(filename, new UTF8Encoding(false));
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("items");
xmlWriter.Close();
xmlDoc.Load(filename);
XmlNode root = xmlDoc.DocumentElement;
XmlElement item = xmlDoc.CreateElement("item");
root.AppendChild(item);
XmlElement itemCategory = xmlDoc.CreateElement("category");
XmlText itemCategoryText = xmlDoc.CreateTextNode("test");
item.AppendChild(itemCategory);
itemCategory.AppendChild(itemCategoryText);
xmlDoc.Save(filename);
You're saving the file twice - once with XmlTextWriter and once with xmlDoc.Save. Saving from the XmlTextWriter isn't adding a BOM - saving with xmlDoc.Save is.
Just save to a TextWriter instead, so that you can specify the encoding again:
using (TextWriter writer = new StreamWriter(filename, false,
new UTF8Encoding(false))
{
xmlDoc.Save(writer);
}
I'd write the XML to a string(builder) instead and then write that string to file.

Categories