Search code examples
c#xmlxml-serialization

XML Serializing Element with prefix


<?xml version="1.0" encoding="UTF-8"?>
<rs:model-request xsi:schemaLocation="http://www.ca.com/spectrum/restful/schema/request ../../../xsd/Request.xsd " xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rs="http://www.ca.com/spectrum/restful/schema/request" throttlesize="100">
<rs:target-models>

I am having trouble understanding the C# XmlSerializer. I have successfully been able to serialize elements that do not have a prefix such as rs:* above. I also have no been able to find how to add the xsi:, xmlns:xsi and xmlns:rs (namespaces?).

Would someone be able to create a simple class to show how to generate the above XML?


Solution

  • Fields, properties, and objects can have a namespace associated with them for serialization purposes. You specify the namespaces using attributes such as [XmlRoot(...)], [XmlElement(...)], and [XmlAttribute(...)]:

    [XmlRoot(ElementName = "MyRoot", Namespace = MyElement.ElementNamespace)]
    public class MyElement
    {
        public const string ElementNamespace = "http://www.mynamespace.com";
        public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
    
        [XmlAttribute("schemaLocation", Namespace = SchemaInstanceNamespace)]
        public string SchemaLocation = "http://www.mynamespace.com/schema.xsd";
    
        public string Content { get; set; }
    }
    

    Then you associate the desired namespace prefixes during serialization by using the XmlSerializerNamespaces object:

    var obj = new MyElement() { Content = "testing" };
    var namespaces = new XmlSerializerNamespaces();
    namespaces.Add("xsi", MyElement.SchemaInstanceNamespace);
    namespaces.Add("myns", MyElement.ElementNamespace);
    var serializer = new XmlSerializer(typeof(MyElement));
    using (var writer = File.CreateText("serialized.xml"))
    {
        serializer.Serialize(writer, obj, namespaces);
    }
    

    The final output file looks like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <myns:MyRoot xmlns:myns="http://www.mynamespace.com" xsi:schemaLocation="http://www.mynamespace.com/schema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <myns:Content>testing</myns:Content>
    </myns:MyRoot>