XML Serialization and namespace prefixes
Solution 1:
To control the namespace alias, use XmlSerializerNamespaces
.
[XmlRoot("Node", Namespace="http://flibble")]
public class MyType {
[XmlElement("childNode")]
public string Value { get; set; }
}
static class Program
{
static void Main()
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("myNamespace", "http://flibble");
XmlSerializer xser = new XmlSerializer(typeof(MyType));
xser.Serialize(Console.Out, new MyType(), ns);
}
}
If you need to change the namespace at runtime, you can additionally use XmlAttributeOverrides
.
Solution 2:
When using generated code from a schema where the types have namespaces this namespace override applies at the root level but the tags within of varying types will have the namespace associated with the class.
I had an occasion to need to use two different generated classes but have different name spaces based on which server I was talking to (don't ask not under my control).
I tried all the overrides offered here and finally gave up and used a kind of brute force method that actually worked pretty well. What I did was serialize to a string. Then use string.replace to change the namespaces then posted the stream from the string by using a stringwriter. Same on the response - capture to a string - manipulate the namespace then deserialize the string from a string writer.
It may not be elegant or use all the fancy overrides but it got the job done.
Solution 3:
I arrived here from another thread that appears "duplicated" but is not in my opinion.
I answered there but is not really legible so let me answer again here.
if your target is to do so something like:
<sample xmlns:sample="urn:sample:ns">
<something>value<something>
<sample:somethingelse>value2</sample:somethingelse>
<new_root xmlns:newns="url:new:ns">
<newns:item1>sample1</newns:item1>
</new_root>
</sample>
I did found a solution for you :).
What you need to do is in the "new_root" class add namespace declaration like this.
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces newns;
and in your item1 classe add the following decoration in order to use your namespace
[XmlElement("item1", Namespace = "url:new:ns")]