Error on XML Document (4,11) - c#

currently i'm developing window game which using isolate storage to process the information. I'm trying to do it in XML however i meet this problem while trying to generate XML document and read it from it. Here's the code and XML generated.
Part of code:
using(IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForAssembly())
{
using(IsolatedStorageFileStream stream =
new IsolatedStorageFileStream("class.xml", FileMode.Create, file))
{
XmlWriterSettings setting = new XmlWriterSettings();
setting.Indent = true;
using(XmlWriter writer = XmlWriter.Create(stream, setting))
{
XmlSerializer serializer = new XmlSerializer(typeof (Student));
serializer.Serialize(stream, new Student()
{
Name = "AhLim"
});
}
}
using(IsolatedStorageFileStream stream =
new IsolatedStorageFileStream("class.xml", FileMode.Open, file))
{
XmlSerializer serializer = new XmlSerializer(typeof (Student));
studentA = (Student) serializer.Deserialize(stream);
}
}
The Student class:
public class Student
{
public String Name { get; set; }
}
The generated XML document :
<?xml version="1.0"?>
<Student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>AhLim</Name>
</Student>
After all, the error as title, XML document error at (4,11) occur on deserialization. I cant figure out the problem as i googled and know the stream issue. Thanks for your all's help

Its because you are writing the xml using the IsolatedStorageFileStream which is writhing in the wrong encoding, try using the XmlWriter you created this will use utf-8 encoding and Deserialization should work fine
using(IsolatedStorageFileStream stream = new IsolatedStorageFileStream("class.xml",FileMode.Create,file))
{
XmlWriterSettings setting = new XmlWriterSettings();
setting.Indent = true;
using (XmlWriter writer = XmlWriter.Create(stream, setting))
{
XmlSerializer serializer = new XmlSerializer(typeof(Student));
serializer.Serialize(writer, new Student() { Name = "AhLim" });
}
}
IsolatedStorageFileStream creates header
<?xml version="1.0"?>
XmlWriter creates header
<?xml version="1.0" encoding="utf-8"?>

I had this same issue. Stupid Microsoft forgot to tell that you student class MUST have a public default constructor. i.e public Student() {}, the promblem will go away.

Related

.NET 6 XmlSerializer Pretty print

I've this sample .NET 6 program printing out a serialised object to XML:
using System.Text;
using System.Xml.Serialization;
var serializer = new XmlSerializer(typeof(Order));
var order = new Order
{
Address = new Address
{
FirstName = "Name"
}
};
await using var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8);
serializer.Serialize(streamWriter, order);
var result = Encoding.UTF8.GetString(memoryStream.ToArray());
Console.WriteLine(result);
public class Order
{
public Address Address;
}
public class Address
{
public string FirstName;
}
This results in this output:
<?xml version="1.0" encoding="utf-8"?><Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Address><FirstName>Name</FirstName></Address></Order>
In .NET 5 and .NET Core 3 similar code results in pretty printed XML like below. How can I format this XML in .NET6?
<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Address>
<FirstName>Name</FirstName>
</Address>
</Order>
To write indented xml you can use XmlTextWriter (instead of just StreamWriter) with Formatting set to Formatting.Indented:
await using var memoryStream = new MemoryStream();
XmlTextWriter streamWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
streamWriter.Formatting = Formatting.Indented;
serializer.Serialize(streamWriter, order);
var result = Encoding.UTF8.GetString(memoryStream.ToArray());
UPD
As #sveinungf wrote in the comment - using XmlWriter.Create is recommended approach, so the code can look like this (also note that Create method can accept StringBuilder or file name which can be more convenient in some scenarios):
await using var memoryStream = new MemoryStream();
var streamWriter = XmlWriter.Create(memoryStream, new()
{
Encoding = Encoding.UTF8,
Indent = true
});
serializer.Serialize(streamWriter, order);
var result = Encoding.UTF8.GetString(memoryStream.ToArray());

How to serialize an UTF 8 xml string

I had this code to create an xml. It used to work as expected, but in the first xml row, the encoding was set as utf-16.
The code was:
public static string SerializeObject<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
Since I need to encode it in UTF-8, I edit it as follows:
public static string SerializeObject<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
XmlWriterSettings settings = new XmlWriterSettings()
{
Encoding = new UTF8Encoding(),
Indent = false,
OmitXmlDeclaration = false
};
using (StringWriter textWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
{
xmlSerializer.Serialize(xmlWriter, toSerialize);
}
return textWriter.ToString();
}
}
The code seems good, but the generated xml has still the row
<?xml version="1.0" encoding="utf-16"?>
and not
<?xml version="1.0" encoding="utf-8"?>
Why? How can I create an utf-8 xml?

Force XDocument to write to String with UTF-8 encoding

I want to be able to write XML to a String with the declaration and with UTF-8 encoding. This seems mighty tricky to accomplish.
I have read around a bit and tried some of the popular answers for this but the they all have issues. My current code correctly outputs as UTF-8 but does not maintain the original formatting of the XDocument (i.e. indents / whitespace)!
Can anyone offer some advice please?
XDocument xml = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), xelementXML);
MemoryStream ms = new MemoryStream();
using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
{
xml.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
String xmlString = sr.ReadToEnd();
}
The XML requires the formatting to be identical to the way .ToString() would format it i.e.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<node>blah</node>
</root>
What I'm currently seeing is
<?xml version="1.0" encoding="utf-8" standalone="yes"?><root><node>blah</node></root>
Update
I have managed to get this to work by adding XmlTextWriter settings... It seems VERY clunky though!
MemoryStream ms = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;
using (XmlWriter xw = XmlTextWriter.Create(ms, settings))
{
xml.Save(xw);
xw.Flush();
StreamReader sr = new StreamReader(ms);
ms.Seek(0, SeekOrigin.Begin);
String blah = sr.ReadToEnd();
}
Try this:
using System;
using System.IO;
using System.Text;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument doc = XDocument.Load("test.xml",
LoadOptions.PreserveWhitespace);
doc.Declaration = new XDeclaration("1.0", "utf-8", null);
StringWriter writer = new Utf8StringWriter();
doc.Save(writer, SaveOptions.None);
Console.WriteLine(writer);
}
private class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
}
Of course, you haven't shown us how you're building the document, which makes it hard to test... I've just tried with a hand-constructed XDocument and that contains the relevant whitespace too.
Try XmlWriterSettings:
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = false;
xws.Indent = true;
And pass it on like
using (XmlWriter xw = XmlWriter.Create(sb, xws))
See also https://stackoverflow.com/a/3288376/1430535
return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();

XmlSerializer Producing XML With No Namespace Prefix

I have to create an XML file with all the elements prefixed, like this:
<ps:Request num="123" xmlns:ps="www.ladieda.com">
<ps:ClientId>5566</ps:ClientId>
<ps:Request>
When i serialize my object, c# is smart and does this:
<Request num="123" xmlns="www.ladieda.com">
<ClientId>5566</ClientId>
<Request>
That is good, because the ps: is not necessary.
But is there a way to force C# to serialize all the prefixes?
My serialize code is this (for incoming object pObject):
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(pObject.GetType());
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
private String UTF8ByteArrayToString(Byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
String constructedString = encoding.GetString(characters);
return (constructedString);
}
First of all, if the consumer of your string were processing XML, then they wouldn't care about the prefix, since it doesn't matter (to XML). Perhaps they don't understand XML, and think they're processing a string (which might need to have the string "ps:" on every element).
Second of all, you should change your code a bit:
XmlSerializer xs = new XmlSerializer(pObject.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8
};
using (XmlWriter writer = XmlWriter.Create(memoryStream, settings))
{
xs.Serialize(writer, pObject);
}
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
This will properly dispose of the stream and XmlWriter if an exception is thrown, stops using the deprecated XmlTextWriter class, and yet still returns a string containing XML written for UTF-8.
Finally, to control the prefix, see "How to: Qualify XML Element and XML Attribute Names":
XmlSerializerNamespaces myNamespaces = new XmlSerializerNamespaces();
myNamespaces.Add("ps", "www.ladieda.com");
XmlSerializer xs = new XmlSerializer(pObject.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8
};
using (XmlWriter writer = XmlWriter.Create(memoryStream, settings))
{
xs.Serialize(writer, pObject, myNamespaces);
}
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
Also check out XmlNamespaceDeclarationsAttribute. Caveat: when deserializing it will only give you namespaces defined by that element, it won't have namespaces defined in parent elements. If you don't have a consistent root type then use the XmlSerializer.Serialize() overload from #John Saunders.
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlnamespacedeclarationsattribute.aspx
In another question #John Saunders suggests using this attribute in regards to controlling xmlns in WSDL: Namespace Prefixes in Wsdl (.net)
From MSDN Sample:
// C#
using System;
using System.IO;
using System.Xml.Serialization;
[XmlRoot("select")]
public class Select {
[XmlAttribute] public string xpath;
[XmlNamespaceDeclarations] public XmlSerializerNamespaces xmlns;
}
public class Test {
public static void Main(string[] args) {
Select mySelect = new Select();
mySelect.xpath = "myNS:ref/#common:y";
mySelect.xmlns = new XmlSerializerNamespaces();
mySelect.xmlns.Add("MyNS", "myNS.tempuri.org");
mySelect.xmlns.Add("common", "common.tempuri.org");
XmlSerializer ser = new XmlSerializer(typeof(Select));
ser.Serialize(Console.Out, mySelect);
}
}
// Output:
// <?xml version="1.0" encoding="IBM437"?>
// <select xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmln:xsi="http://www.w3.org/2001/XMLSchema-instance"
// xmlns:common="common.tempuri.org" xmlns:MyNS="myNS.tempuri.org" xpath="myNS:ref/#common:y" />

How do I add a default namespace with no prefix using XMLSerializer

I am trying to generate an XML document that contains the default namespace without a prefix using XmlSerializer, e.g.
<?xml version="1.0" encoding="utf-8" ?>
<MyRecord ID="9266" xmlns="http://www.website.com/MyRecord">
<List>
<SpecificItem>
Using the following code ...
string xmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord));
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, string.Empty);
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, myRecord, xmlnsEmpty);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlizedString = this.UTF8ByteArrayToString(memoryStream.ToArray());
and class structure ...
[Serializable]
[XmlRoot("MyRecord")]
public class ExportMyRecord
{
[XmlAttribute("ID")]
public int ID { get; set; }
Now, I've tried various options ...
XmlSerializer xs = new XmlSerializer
(typeof(ExportMyRecord),"http://www.website.com/MyRecord");
or ...
[XmlRoot(Namespace = "http://www.website.com/MyRecord", ElementName="MyRecord")]
gives me ...
<?xml version="1.0" encoding="utf-8"?>
<q1:MylRecord ID="9266" xmlns:q1="http://www.website.com/MyRecord">
<q1:List>
<q1:SpecificItem>
I need the XML to have the namespace without the prefix as it's going to a third party provider and they reject all other alternatives.
There you go:
ExportMyRecord instance = GetInstanceToSerializeFromSomewhere();
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, "http://www.website.com/MyRecord");
var serializer = new XmlSerializer(
instance.GetType(),
"http://www.website.com/MyRecord"
);
Here's a generic implementation that can be used for any type:
public static void Serialize<T>(T instance, string defaultNamespace, Stream stream)
{
var namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, defaultNamespace);
var serializer = new XmlSerializer(typeof(T), defaultNamespace);
serializer.Serialize(stream, instance, namespaces);
}

Categories