Specify encoding XmlSerializer - c#

I've a class correctly defined and after serialize it to XML I'm getting no encoding.
How can I define encoding "ISO-8859-1"?
Here's a sample code
var xml = new XmlSerializer(typeof(Transacao));
var file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "transacao.xml"),FileMode.OpenOrCreate);
xml.Serialize(file, transacao);
file.Close();
Here are the beginning of xml generated
<?xml version="1.0"?>
<requisicao-transacao xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<dados-ec>
<numero>1048664497</numero>

The following should work:
var xml = new XmlSerializer(typeof(Transacao));
var fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "transacao.xml");
var appendMode = false;
var encoding = Encoding.GetEncoding("ISO-8859-1");
using(StreamWriter sw = new StreamWriter(fname, appendMode, encoding))
{
xml.Serialize(sw, transacao);
}
If you don't mind me asking, why do you need ISO-8859-1 encoding in particular? You could probably use UTF-8 or UTF-16 (they're more commonly recognizable) and get away with it.

Create a StreamWriter with the desired encoding:
System.Text.Encoding code = *WhateverYouWant*
StreamWriter sw = new StreamWriter(file, code);

Related

How to get encoding of xml file?

How to get the information of encoding in a xml file using c#?
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml version="1.0" encoding="Windows-1252"?>
I know how to read in the elements and attributes...
But I have to make a definition by cases in my deserialization method:
Depending on the encoding type of the xml I have to use encoding_windows or encoding_utf for StreamReader
var encoding_windows = Encoding.GetEncoding("Windows-1252");
var encoding_utf = Encoding.GetEncoding("utf-8");
var sr = new StreamReader(current_file, encoding_windows, true);
As your are using StreamReader try this :
var sr = new StreamReader(current_file);
var encodingCurrentFile = sr.CurrentEncoding.EncodingName;
Console.WriteLine(encodingCurrentFile);
encodingCurrentFile is your current encoding name.

c# XML \r \n error

I have code for read xml:
string xmlread = new StreamReader(response.GetResponseStream()).ReadToEnd();
Custom custom = new Custom();
TextReader txtReader = new StreamReader(Convert.ToString(xmlread));
XmlSerializer xmlSerializer = new XmlSerializer(typeof(custom));
custom = (Custom)xmlSerializer.Deserialize(txtReader);
but xml has the form
<?xml version=\"1.0\"?>\n<instacheat>\n <hash>5d02c2151c9d147b2219b371b7d383b3665e</hash>\n</instacheat>\n\r\n
and because gives me an error "It contains invalid characters."
Try getting the stream reader to detect the text encoding:
string xmlread = new StreamReader(response.GetResponseStream(), true).ReadToEnd();
To get rid of \r\n, I suggest using a regex as a quick solution
xmlread = System.Text.RegularExpressions.Regex.Replace(xmlread, #"\\r|\\n", "")

Deserialization error in XML document(1,1)

I have an XML file that I deserialize, the funny part is the XML file is the was serialized
using the following code:
enter code here
var serializer = new XmlSerializer(typeof(CommonMessage));
var writer = new StreamWriter("OutPut.txt");
serializer.Serialize(writer, commonMessage);
writer.Close();
And i m trying to deserialized it again to check if the output match the input.
anyhow here is my code to deserialize:
var serializer = new XmlSerializer(typeof(CommonMessage));
var reader = new StringReader(InputFileName);
CommonMessage commonMessage = (CommonMessage)serializer.Deserialize(reader);
Replace StringReader with StreamReader and it will work fine. StringReader reads value from the string (which is file name in your case).
I just had the same error message but different error source. In case someone has the same problem like me. I chopped off the very first char of my xml string by splitting strings. And the xml string got corrupted:
"?xml version="1.0" encoding="utf-16"?> ..." // my error
"<?xml version="1.0" encoding="utf-16"?> ..." // correct
(1,1) means basically first char of the first line is incorrect and the string can't be deserialized.
include in your CommonMessage class the XmlRoot element tag with your xmlroot eg:[XmlRoot("UIIVerificationResponse")]
You should disable the order mark in the StreamWriter constructor like this:
UTF8Encoding(false)
Full sample:
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(false)))
{
xmlSerializer.Serialize(writer, objectToSerialize, ns);
return Encoding.UTF8.GetString(stream.ToArray());
}

Unknown chr being output after XSL Compiled Transform

my code is outputting some weird character at the very start of my XSLT output XML and neither Visual Studio 2008 or notepad show it up. But it's definitely there because VS lets me delete it and will then auto-format the XML properly. How do I stop this? Here's my code:
// create the readers for the xml and xsl
XmlReader reader = XmlReader.Create(
new StringReader(LoadFileAsString(MapPath(xslPath)))
);
XmlReader input = XmlReader.Create(
new StringReader(LoadFileAsString(MapPath(xmlPath)))
);
// create the xsl transformer
XslCompiledTransform t = new XslCompiledTransform(true);
t.Load(reader);
// create the writer which will output the transformed xml
StringBuilder sb = new StringBuilder();
//XmlWriterSettings tt = new XmlWriterSettings();
//tt.Encoding = Encoding.Unicode;
XmlWriter results = XmlWriter.Create(new StringWriter(sb));//, tt);
// write the transformed xml out to a stringbuilder
t.Transform(input, null, results);
// return the transformed xml
WriteStringAsFile(MapPath(outputXmlPath), sb.ToString());
public static string LoadFileAsString(string fullpathtofile)
{
string a = null;
using (var sr = new StreamReader(fullpathtofile))
a = sr.ReadToEnd();
return a;
}
public static void WriteStringAsFile(string fullpathtofile, string content)
{
File.WriteAllText(fullpathtofile, content.Trim(), Encoding.Unicode);
}
That thing at the beginning of your XML output document is most likely a byte-order-mark or BOM, which indicates whether the bytes in your Unicode output are in big-endian or little-endian order.
This BOM might be useful for consumers of your XML document; however, in some cases it might lead to problems and then it is better not to create it.
You can specify whether a BOM is created using the Encoding specified via XmlWriterSettings:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Encoding = new UTF8Encoding(false);
The code above will create your document using UTF8 encoding. This is most likely what you want to have unless your consuming system explicitly asks for UTF16/Unicode encoding or you are dealing with Asian character.
To create a UTF16/Unicode encoded document use UnicodeEncoding with the second parameter set to false:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Encoding = new UnicodeEncoding(false, false);

Make xml more readable

Is there any way to take an xml string in .net and make it easyer to read?
what i mean is can i convert this:
<element1><element2>some data</element2></element1>
to this:
<element1>
<element2>
some data
</element2>
</element1>
is there any built in class for this? as sql server 2005 seems to remove all formatting on xml to save space or some thing...
If you're using .NET 3.5, you can load it as an XDocument and then just call ToString() which will indent it appropriately. For example:
using System;
using System.Xml.Linq;
public class Test
{
static void Main()
{
string xml = "<element1><element2>some data</element2></element1>";
XDocument doc = XDocument.Parse(xml);
xml = doc.ToString();
Console.WriteLine(xml);
}
}
Result:
<element1>
<element2>some data</element2>
</element1>
If you're writing it to a file or other stream, then XDocument.Save will (by default) indent it too.
(I believe XElement has all the same features, if you don't really need an XDocument.)
How do you save / write the XML back to a file ?
You can create an XmlWriter and pass it an XmlWriterSettings instance, where you set the Indent property to true:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create (outputStream, settings);
You can load the string into an XDocument object and save it to a string again:
XDocument doc = XDocument.Load(new StringReader(xmlString));
StringWriter writer = new StringWriter();
doc.Save(writer);
string readable = writer.ToString();
That will give you the xml formatted this way:
<?xml version="1.0" encoding="utf-16"?>
<element1>
<element2>some data</element2>
</element1>
Have a look at
XmlWriterSettings
http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx
you can define Indent and IndentChars
First of all, you have tagged C# and VB.NET both. So my answer will be for both of them.
You can define function which get XML string as a parameter in type of String.
Let's say;
You created a function as :
[VB]
Private Function PrettyXML(XMLString As String) As String
Dim sw As New StringWriter()
Dim xw As New XMLWriter(sw)
xw.Formatiing = Formatting.Indented
xw.Indentation = 4
Dim doc As New XMLDocument
doc.LoadXML(XMLString)
doc.Save(xw)
Return sw.ToString()
End Function
Then you can simpyl call this function as:
Dim myXML As String = "<element1><element2>some data</element2></element1>"
Dim myPrettyXML As String
myPrettyXML = PrettyXML(myPrettyXML)
[C#]
Private String PrettyXML(string XMLString)
{
StringWriter sw = new StringWriter();
XMLTextWriter xw = new XmlTextWriter(sw);
xw.Formatiing = Formatting.Indented;
xw.Indentation = 4;
XmlDocument doc = new XmlDocument();
doc.Save(xm);
return sw.ToString();
}
Then you can simply call this function as:
string myXML = "<element1><element2>some data</element2></element1>";
string myPrettyXML = "";
myPrettyXML = PrettyXML(myPrettyXML);
NOTE: I have not tried C# version, but it should work.
Hope this helps..

Categories

Resources