Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colon character getting encoded to x003A in xml element serialization process

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!

like image 201
ANR Upgraded Version Avatar asked Dec 10 '17 10:12

ANR Upgraded Version


1 Answers

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);
like image 127
Evk Avatar answered Sep 22 '22 20:09

Evk