2
<?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?

blgrnboy
  • 4,877
  • 10
  • 43
  • 94

1 Answers1

4

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>
RogerN
  • 3,761
  • 11
  • 18
  • i tryed this is fine when you want to a prefix to the root but i want to add a prefix to also other node under the root. it has been added but to the next node – Hamit YILDIRIM Sep 09 '15 at 14:16