Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify XML serialization attributes to support namespace prefixes during deserialization in .NET?

I have a following XML:

<person xmlns:a="http://example.com" xmlns:b="http://sample.net">     <a:fName>John</a:fName>     <a:lName>Wayne</a:lName>     <b:age>37</b:age> </person> 

How do I define XML serialization attributes on a class to support described scenario?

like image 442
Piotr Owsiak Avatar asked Aug 10 '09 12:08

Piotr Owsiak


People also ask

Which is the namespace for XML serialization?

Remarks. The XmlSerializerNamespaces contains a collection of XML namespaces, each with an associated prefix. The XmlSerializer uses an instance of the XmlSerializerNamespaces class to create qualified names in an XML document.

What is the correct way of using XML serialization?

XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.

Which of the following attribute controls XML serialization of the attribute target as an XML root element?

XmlRootAttribute Class (System.Xml.Serialization) Controls XML serialization of the attribute target as an XML root element.

What is XML serialization and Deserialization?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.


1 Answers

You'll need to indicate which namespaces each field requires by using Namespace of XmlElement attribute. This will allow you to associate a field with a particular namespace, but you'll also need to expose a property on your class that returns type XmlNamespaceDeclarations in order to get the prefix association.

See documentation and sample below:

[XmlRoot(ElementName = "person")] public class Person {     [XmlElement(Namespace = "http://example.com")]     public string fname;      [XmlElement(Namespace = "http://sample.com")]     public string lname;      [XmlNamespaceDeclarations]     public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();      public Person()     {         xmlns.Add("a", "http://example.com");         xmlns.Add("b", "http://sample.com");     } } 
like image 84
Zach Bonham Avatar answered Oct 02 '22 01:10

Zach Bonham