I have got XML response from my client. I can't deserialize the XML as string, it throws an Illegal characters in path error. So now I save the file in temp folder and retrieve that. Is it possible to do the deserialize without saving the XML file first?
string xml = Post();
XmlSerializer deserializer = new XmlSerializer(typeof(Envelope));
TextReader reader = new StreamReader(xml); <-- Illegal characters in path error -->
object obj = deserializer.Deserialize(reader);
Envelope XmlData = (Envelope)obj;
reader.Close();
Edit 1 -
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
using (TextWriter writer = new StreamWriter(xml)) <-- StringWriter is Possible here? -->
{
serializer.Serialize(writer, XmlData);
}
Instead of a StreamReader, use a StringReader, that takes a string as constructor parameter.
TextReader reader = new StringReader(xml);
For writing, use this:
string output;
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
using (TextWriter writer = new StreamWriter(xml)) <-- StringWriter is Possible here? -->
{
serializer.Serialize(writer, XmlData);
output = writer.ToString();
}
Related
**
I want to add XML schema and XML element together in same file. Because this xml file we will need to generate through C# based on specific record. So, i am looking some code help how can i write together XMLSchema and XML element in same file and inside same element. Please check attachment.
<Survey>
**Here i want XML schema**
**Here i want XML element**
</Survey>
Working Code Example
SiteSurveyX siteSurveyX = new SiteSurveyX();
XmlTextReader reader = new XmlTextReader("c:\\temp\\TestSiteSchema.xsd");
//siteSurveyX.SurveySchema = XmlSchema.Read(reader, null);
XmlSchema myschema = XmlSchema.Read(reader, null);
string filePath = HelperFunctions.SurveyFilePath + routeName;
////Get all node record from DB
siteSurveyX.Survey = routeService.GetRouteDetailForXML(routeId, Convert.ToString(ddlRoute.Text), chkCurrentInterruption.Checked);
using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
lblStatus.Text = "Preparing file";
stream.Close();
stream.Dispose();
//Convert record in XML
XmlSerializer serializer = new XmlSerializer(typeof(SiteSurveyX));
using (StreamWriter writer = new StreamWriter(filePath, true))
{
serializer.Serialize(writer, siteSurveyX);
lblStatus.Text = "Ready";
}
}
It's done with this code.
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.
I use a TextWriter to serialize, because it's easy to switch between string serialization and file serialization:
Serialize to string;
TextWriter stringWriter = new StringWriter();
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(stringWriter , objetToSerialize)
return stringWriter.ToString();
Serialize to file;
TextWriter fileWriter = new StreamWriter(targetXMLFileName, true, Encoding.UTF8);
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(fileWriter , objetToSerialize)
fileWriter.Close();
My problem is that when serializing to string, it creates a UTF-16 ("?xml version="1.0" encoding="utf-16"?"), and TestWriter encoding property is ReadOnly
I have tried:
var memoryStream = new MemoryStream();
TextWriter stringWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
XmlSerializer serializer = XmlSerializer(typeof(ObjectType))
serializer.Serialize(stringWriter , objetToSerialize)
return stringWriter.ToString();
But it doesn't work. Instead of an XML Document it produces this string: "System.IO.StreamWriter" O_o
How can I initialize the TextWriter to UTF-8 Encoding
Instead of stringWriter.ToString, use
string xml = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
return xml;
That will convert the memory stream you wrote to, to a printable XML with utf-8 in the header.
Person person = GetPerson();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(typeof(Person));
string personText = string.Empty;
using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, new XmlWriterSettings() { Encoding = Encoding.UTF8 }))
{
serializer.Serialize(xmlWriter, person, ns);
xmlWriter.Flush();
personText = Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
string path = #"D:\person.xml";
// Write method 1:
File.WriteAllText(path, personText);
// Write method 2:
using (StreamWriter streamWriter = new StreamWriter(path, false , Encoding.UTF8))
{
streamWriter.Write(personText);
}
// Read the xml
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
return XDocument.Load(XmlReader.Create(fileStream));
}
When I read the xml after writing using method 2, I get this Data at the root level is invalid. Line 1, position 1. But it works fine using method 1.
What is causing this? Any pointers appreciated.
The problem is that both the StreamWriter and the XmlWriter are adding a byte-order-mark.
Options:
String the BOM from personText to start with
Pass new UTF8Encoding(false) instead of Encoding.UTF8 for the StreamWriter
Pass new UTF8Encoding(false) instead of Encoding.UTF8 for the XmlWriter
Avoid converting to text and back again in the first place: you've got the binary data in the MemoryStream, why not just dump that to disk?
http://james.newtonking.com/projects/json/help/
How come when I use "DeserializeXmlNode" and my JSON gets converted to an XML document
then convert my XML document into a string like this
string strXML = "";
StringWriter writer = new StringWriter();
xmlDoc.Save(writer);
strXML = writer.ToString();
It includes
<?xml version="1.0" encoding="utf-16"?>
I did not add this, how do I remove it?
an XML without that line is not a valid XML file!
that line is called the XML Declaration
as an example, check out the OData XML from Netflix on Catalog Titles, can you see that first line?
http://odata.netflix.com/Catalog/Titles
Use XmlWriter with StringBuilder instead of StringWriter
var strXML = "";
var writer = new StringBuilder();
var settings = new System.Xml.XmlWriterSettings() { OmitXmlDeclaration = true};
var xmlWriter = System.Xml.XmlWriter.Create(strXML, settings);
xmlDoc.Save(xmlWriter);
strXML = writer.ToString();