Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Serialization and namespace prefixes

I'm looking for a way with C# which I can serialize a class into XML and add a namespace, but define the prefix which that namespace will use.

Ultimately I'm trying to generate the following XML:

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

I know with both the DataContractSerializer and the XmlSerializer I can add a namespace, but they seem to generate a prefix internally, with something that I'm not able to control. Am I able to control it with either of these serializers (I can use either of them)?

If I'm not able to control the generation of the namespaces will I need to write my own XML serializer, and if so, what's the best one to write it for?

like image 640
Aaron Powell Avatar asked Feb 26 '10 06:02

Aaron Powell


People also ask

Is a namespace for XML serialization?

The central class in the namespace is the XmlSerializer class. To use this class, use the XmlSerializer constructor to create an instance of the class using the type of the object to serialize. Once an XmlSerializer is created, create an instance of the object to serialize.

What is namespace prefix in XML?

When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

What is XML serialization?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

What is prefix of XML file?

The prefix xml is by definition bound to the namespace name http://www.w3.org/XML/1998/namespace . It MAY, but need not, be declared, and MUST NOT be bound to any other namespace name. Other prefixes MUST NOT be bound to this namespace name, and it MUST NOT be declared as the default namespace.


1 Answers

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.

like image 106
Marc Gravell Avatar answered Sep 18 '22 13:09

Marc Gravell