XML Serialization Prefixes and Namespaces

I am looking for a way with C # that I can serialize a class in XML and add a namespace, but define a prefix that this namespace will use.

I end up trying to create the following XML:

<myNamespace:Node xmlns:myNamespace="..."> <childNode>something in here</childNode> </myNamespace:Node> 

I know with both DataContractSerializer and XmlSerializer , I can add a namespace, but they seem to create a prefix inside, with something that I cannot control. Can I control it using any of these serializers (I can use any of them)?

If I cannot control the generation of namespaces, I will need to write my own XML serializer, and if so, which one is better to write?

+48
c # xml-serialization datacontractserializer xmlserializer
Feb 26 '10 at 6:01
source share
2 answers

To manage 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 run time, you can optionally use XmlAttributeOverrides .

+82
Feb 26 2018-10-12T00
source share
— -

When using the generated code from a schema where types have namespaces, this namespace redefinition is applied at the root level, but tags within different types will have a namespace associated with the class.

I had to use two different generated classes, but with different names that I spoke in (don't ask, not under my control).

I tried all the redefinitions suggested here, and finally gave up and used a kind of brute force method that really worked very well. What I did was serialized for the string. Then use string.replace to change the namespaces, and then send the stream from the string using a stringwriter. The same thing in the answer - capturing to a string - manipulates the namespace and then deserializes the string from the string entry.

It may not be elegant or use all the fancy redefinitions, but it did its job.

+3
Feb 28 '14 at 2:59
source share



All Articles