I have defined type as Example as shown below, after instantiating a object and serializing using XmlSerializer, i am getting x003A
instead of colon :
Here's my code:
public class Example
{
[XmlElement("Node1")]
public string Node1 { get; set; }
[XmlElement("rd:Node2")]
public string Node2 { get; set; }
}
Serialization code
Example example = new Example { Node1 = "value1", Node2 = "value2" };
XmlSerializerNamespaces namespaceSerializer = new XmlSerializerNamespaces();
namespaceSerializer.Add("rd", @"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Example));
string path = System.Windows.Forms.Application.StartupPath + "//example.xml";
using (StreamWriter writer = new StreamWriter(path))
{
serializer.Serialize(writer, example, namespaceSerializer);
}
Expected Result
<?xml version="1.0" encoding="utf-8"?>
<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Node1>value1</Node1>
<rd:Node2>value2</rd:Node2>
</Example>
Actual Result:
<?xml version="1.0" encoding="utf-8"?>
<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Node1>value1</Node1>
<rd_x003A_Node2>value2</rd_x003A_Node2>
</Example>
Any help and direction in this are greatly appreciated. Thanks in advance!
You have to do it like this:
public class Example {
[XmlElement("Node1")]
public string Node1 { get; set; }
// define namespace like this, not with a prefix
[XmlElement("Node2", Namespace = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner")]
public string Node2 { get; set; }
}
Then when serializing:
var serializer = new XmlSerializer(typeof(Example));
var ns = new XmlSerializerNamespaces();
// map prefix to namespace like this
ns.Add("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
var ms = new MemoryStream();
// use namespaces while serializing
serializer.Serialize(ms, new Example {
Node1 = "node1",
Node2 = "node2"
}, ns);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With